定位new的析构

版权声明: https://blog.csdn.net/dashoumeixi/article/details/82868648
#include <new>
#include <string>
const int BUFF_SIZE = 512;
using namespace std;
class testing{
    string words;
    int num;
public:
    testing(const string &s = "testing",int n =0){
        words = s;
        num = n;
        cout << "construct :" << s  << endl;
    }
    ~testing(){
        cout << "~testing :" << words<< endl;
    }
    void show() const { cout << words << "," << num << endl;}
};
int main(int argc, char *argv[])
{
   //被定位的内存
    char *mem = new char[BUFF_SIZE];
    cout << "mem:" << (void*)mem << endl;

    testing *p1, *p2 ,*p3;
    p1 = new (mem) testing("im p1"); //定位在mem
    p2 = new testing("im in heap",20); //默认在heap
    cout << "p1:" << p1 << ", p2:" << p2 << endl;
    p1->show();
    p2->show();
    p3 = new (mem)testing("im p3"); //再次定位在mem. 之前的数据将被覆盖
    cout << "p3:" << p3 << endl;
    p3->show();
    cout << "p1:" << p1 << endl;
    p1->show();
    delete[] mem; //只释放了mem本身的空间,并不执行析构. mem只是一个char数组


}

下面的一个例子将修复上述的错误. 显示的调用析构

//被定位的内存
    char *mem = new char[BUFF_SIZE];
    cout << "sizeof(testing) :" << sizeof(testing) << endl;
    cout << "mem:" << (void*)mem << endl;

    testing *p1, *p2 ,*p3;
    p1 = new (mem) testing("im p1"); //定位在mem
    p2 = new testing("im in heap",20); //默认在heap
    cout << "p1:" << p1 << ", p2:" << p2 << endl;
    p1->show();
    p2->show();
    p3 = new (mem+sizeof(testing))testing("im p3");
    cout << "p3:" << p3 << endl;
    p3->show();
    cout << "p1:" << p1 << endl;
    p1->show();
    delete p2;
    //注意释放顺序, 别把mem 先释放了
    p3->~testing();
    p1->~testing();

    delete[] mem; //只释放了mem本身的空间,并不执行析构. mem只是一个char数组

猜你喜欢

转载自blog.csdn.net/dashoumeixi/article/details/82868648