c++ 用布局NEW 管理类对象

 #include <iostream>
#include <string>
#include <new> // 引用布局new
const int BUF = 512;
using namespace std;
/* 主要演示在布局new如何存放对象与释放对象
* 因为变量都是对象指针,本来都需要人工释放对象
* 但使用布局NEW 会有所不同
*/
class TestClass{
private:
    string words;
public:
    TestClass(char * str = "default string"){
        words = str;
    }
    ~TestClass(){}
    void show() const{
        cout << words << endl;
    }
};

int main()
{
    char * buffer = new char[BUF];
    TestClass *tc1, *tc2;
    // 使用布局new 把对象放在数组里,不申请堆内存
    tc1 = new (buffer) TestClass("Buffer");
    tc2 = new TestClass("Heap"); // 申请堆内存,把对象放在堆里
    cout << "buffer addr:= " << (void *)buffer << endl;
    cout << "tc1 addr:= " << tc1 << " data:= ";
    tc1->show();
    cout << "tc2 addr:= " << tc2 << " data:= ";
    tc2->show();

    tc1->~TestClass();// 需要手工调用析构函数,
    delete tc2; // 释放对象 tc2
    delete [] buffer; // 释放缓存;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值