C++ new操作符

#include <iostream>
#include <new>
using namespace std;

int main()
{
    //operator new申请一块内存空间,用来存储string对象
    void *rawMemory = operator new(sizeof(string));
    //用string指针指向此块内存空间,使这块内存被视为一个string对象
    string *ps = static_cast<string *>(rawMemory);
    //使用placement new构造此块内存中的对象
    new (ps) string ();
    cout << ps->length() << endl;
    ps->append("abcdefg");  //追加内容
    cout << ps->length() << endl;
    ps->~string(); //析构
    cout << ps->length() << endl;
    operator delete(ps);    //释放空间

    return 0;
}

operator new申请的空间为未初始化的void *空间,对于operator new申请的内存,不可以直接用delete来释放(此操作包含析构和释放两步操作),只可以用operator delete来释放相应的区域。在此处初始化使用的是placement new操作符,使用析构函数对此处区域进行析构之后可释放内存区域。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值