前面学习到通过new运算符创建的对象指针只有通过显式的使用delete才能调用析构函数。那如果对象指针使用的是定位new运算符,要如何确保析构函数被调用呢?看以下例子:
#include<iostream>
using namespace std;
class A
{
private:
int num;
public:
A(const int n) { num = n; cout << num << " constructed" << endl; }
~A() { cout << num << " destroyed." << endl; }
};
int main(void)
{
char* buffer = new char[512];
A* pa1 = new(buffer) A(1);
A* pa2 = new(buffer) A(2);
delete pa1;//成功释放
delete pa2;//释放失败
}
运行结果:
1 constructed
2 constructed
2 destroyed.
-572662307 destroyed.
触发断点:HEAP[placenew1.exe]: Invalid address specified to RtlValidateHeap( 01590000, 0159E3E0 )
1.第一个问题,为什么pa2会释放出错?
pa2释放失败的原因是因为二者指向的地址是同一个,pa1已经将这块空间释放了,pa2再释放一次就会出错。
事实上,delete pa1等效于delete buffer,也因此而释放成功了,但这样做是不安全的,一是会出现例子中后续delete的失败,二是delete pa1等效于delete buffer,也就是说只释放了首地址。
正确的做法应该是
delete []buffer;
这其实说明了一个规则,就是delete要释放的是由new开辟的空间,而对于pa1、pa2来说,使用定位new运算符并没有开辟空间,因此使用delete释放就是错误的。
修改后的代码:
#include<iostream>
using namespace std;
class A
{
private:
int num;
public:
A(const int n) { num = n; cout << num << " constructed" << endl; }
~A() { cout << num << " destroyed." << endl; }
};
int main(void)
{
char* buffer = new char[512];
A* pa1 = new(buffer) A(1);
A* pa2 = new(buffer) A(2);
delete[] buffer;
}
运行结果:
1 constructed
2 constructed
2.这里就出现了第二个问题,虽然内存空间被顺利释放了,但是析构函数没有被调用。
原因在本文第一句话提到了,由new运算符声明的指针需要显式的delete才能调用析构函数,但现在delete定位new运算符声明的指针又会出错,怎么办呢?
解决办法就是显式的调用析构函数,这也是少有的几个需要显式调用析构函数的情况:
#include<iostream>
using namespace std;
class A
{
private:
int num;
public:
A(const int n) { num = n; cout << num << " constructed" << endl; }
~A() { cout << num << " destroyed." << endl; }
};
int main(void)
{
char* buffer = new char[512];
A* pa1 = new(buffer) A(1);
A* pa2 = new(buffer) A(2);
pa2->~A();//注意后创建的先释放,因为有时候后创建的对象可能使用了先创建对象的资源
pa1->~A();
delete[] buffer;
}
运行结果:
1 constructed
2 constructed
2 destroyed.
2 destroyed.
3.最后一个问题,为什么两次析构函数都是2 destroyed?
原因在于pa2使用定位new运算符的起始位置与pa1相同,因此后创建的pa2把pa1的内容挤掉了,代码更改:
#include<iostream>
using namespace std;
class A
{
private:
int num;
public:
A(const int n) { num = n; cout << num << " constructed" << endl; }
~A() { cout << num << " destroyed." << endl; }
};
int main(void)
{
char* buffer = new char[512];
A* pa1 = new(buffer) A(1);
A* pa2 = new(buffer + sizeof(pa1)) A(2);
pa2->~A();
pa1->~A();
delete[] buffer;
}
运行结果:
1 constructed
2 constructed
2 destroyed.
1 destroyed.
本文探讨了使用定位new运算符声明的类对象指针在调用析构函数时遇到的问题。首先解释了为何pa2的释放会导致错误,因为两次释放同一内存空间。接着指出,定位new并未开辟新空间,因此使用delete释放是错误的,正确的做法是使用`delete []buffer;`。接着讨论了解决析构函数未被调用的问题,需要显式调用析构函数。最后解答了为何两次析构函数显示`2 destroyed`,原因是pa2覆盖了pa1的内容。
680

被折叠的 条评论
为什么被折叠?



