【发布时间】:2010-12-13 06:24:49
【问题描述】:
我只是想知道这三种调用析构函数的方法是否有任何显着/严重的差异。考虑以下代码。也请考虑main()中提到的两种情况。
class Sample
{
public:
~Sample()
{
cout << "destructor called" << endl;
}
void destroyApproach1() { this->~Sample(); }
void destroyApproach2() { delete this; }
};
void destroyApproach3(Sample *_this)
{
delete _this;
}
void TestUsingNew()
{
Sample *pSample[] = { new Sample(), new Sample(),new Sample()};
pSample[0]->destroyApproach1();
pSample[1]->destroyApproach2();
destroyApproach3(pSample[2]);
}
void TestUsingPlacementNew()
{
void *buf1 = std::malloc(sizeof(Sample));
void *buf2 = std::malloc(sizeof(Sample));
void *buf3 = std::malloc(sizeof(Sample));
Sample *pSample[3] = { new (buf1) Sample(), new (buf2) Sample(), new (buf3) Sample()};
pSample[0]->destroyApproach1();
pSample[1]->destroyApproach2();
destroyApproach3(pSample[2]);
}
int main()
{
//Case 1 : when using new
TestUsingNew();
//Case 2 : when using placement new
TestUsingPlacementNew();
return 0;
}
请在回复时具体说明您要回答的是哪种情况:情况 1 或情况 2,或两者兼而有之!
另外,我试图以这种方式编写TestUsingPlacementNew(),但它会引发运行时异常(MSVC++2008)。我不明白为什么:
void TestUsingPlacementNew()
{
const int size = sizeof(Sample);
char *buffer = (char*)std::malloc( size * 3);
Sample *pSample[] = { new (buffer) Sample(), new (&buffer[size]) Sample(),new (&buffer[2*size]) Sample()};
pSample[0]->destroyApproach1();
pSample[1]->destroyApproach2();
destroyApproach3(pSample[2]);
}
也许,内存填充和/或对齐可能是原因?
相关话题:Destructor not called after destroying object placement-new'ed
【问题讨论】:
标签: c++ malloc destructor new-operator placement-new