c++ do I need to manually delete a void* pointer which is then pointing to another concrete type?
假设我有一个指针
在大多数地方,人们说只有当有
这完全取决于你所指的
正确(
1 2 3 4 5 6 | int* a = new int; void* p = a; //somewhere later... delete static_cast<int*>(p); |
坏(
1 2 3 4 5 6 | int a = 0; void* p = &a; //somewhere later... delete static_cast<int*>(p); |
回答注释代码,执行以下操作:
1 2 3 4 | int* a = new int; void* p = a; delete p; |
永远不会好。你不应该通过
旁注:在现代C++中,你不应该使用EDCOX1 2或EDCOX1 1,坚持智能指针或标准容器。
简短的回答是:"视情况而定"。
In most places people say
delete only happen when there isnew .
就目前而言,这是真的。为了避免浪费资源并确保正确调用所有析构函数,每个
当抛出异常时,可能会变得棘手,这是现代C++程序员通常避免使用EDCOX1 2和EDCOX1 1的原因之一。相反,他们使用智能指针
But in this case, it's not …
记住这句话…当存在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | int *a = new int(); void *p = a; if (SomeTest()) { delete a; } else { a = nullptr; } // This line is needed if SomeTest() returned false // and undefined (dangerous) if SomeTest() returned true delete static_cast<int *> (p); |
需要最后一行代码吗?
另一方面,如果函数
C++标准称,在已经删除的对象上调用EDCOX1×1,导致"未定义的行为",这意味着任何事情都可能发生。看到这样的问题:在双重删除中会发生什么?
does C++ itself remember to release that memory?
不是因为调用
do I need to manually delete
是:如果此处需要删除指向的对象,并且只有