@
enenaaa [这里](
https://stackoverflow.com/questions/14187006/is-calling-destructor-manually-always-a-sign-of-bad-design)
有一个讨论, 是和 placement new 相关的.
现在比较明确的是, 这个问题应该是'未定义行为'的锅.
>> cat a.cxx
#include <vector>
#include <iostream>
int* g_p = NULL;
class Holder
{
int* p;
public:
Holder(int x) {
p=new int();
*p=x;
if(x == 3) {
g_p = p;
}
}
~Holder() {
std::cout<< "[destruct] pointer:" << p << " value:" << *p << std::endl;
delete p;
}
};
void foo(){
std::vector<Holder> v;
v.reserve(3);
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);
std::cout << "manual destruct start" << std::endl;
v[1].~Holder();
std::cout << "manual destruct end" << std::endl;
std::cout << "befor destruct" << std::endl;
std::cout<< "pointer:" << g_p << " value:" << *g_p << std::endl;
std::cout << "befor destruct end" << std::endl;
}
int main(int argc, char *argv[])
{
foo();
std::cout << "[out foo] pointer:" << g_p << " value:" << *g_p << std::endl;
return 0;
}
>> g++ a.cxx -o a
>> ./a
manual destruct start
[destruct] pointer:0x771c60 value:2
manual destruct end
befor destruct
pointer:0x771c80 value:3
befor destruct end
[destruct] pointer:0x771c40 value:1
[destruct] pointer:0x771c60 value:0
[destruct] pointer:0x771c80 value:3
[out foo] pointer:0x771c80 value:7806032
linux & g++下的结果, 比较有意思的是, 在 manually call dtor 之后, 0x771c60 的值是 0(多次运行, 值都是 0), 所以, 内存依然是有效的(?), 如果上述推论成立, 那么再次 delete 自然不会 double free.