定位new的析构

#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数组

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值