在固定位置new一个对象源代码

// usenew.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <new> using namespace std; class CNew { public: CNew(int nVal) { m_nData = nVal; cout << "constructor of CNew has been called!" << endl; } ~CNew() { cout << "destructor of CNew has been called!" << endl; } public: void PrintInfo() { cout << "data = " << m_nData << endl; } private: int m_nData; }; void TestForNew(); char g_szBuf[300] = {0}; //stack memory int _tmain(int argc, _TCHAR* argv[]) { memset(g_szBuf, 0, sizeof(g_szBuf)); TestForNew(); return 0; } void TestForNew() { //1. 预分配缓冲 char* pszBuf = new char[sizeof(CNew)];//new memory if (NULL == pszBuf) { cout << "get memory failed..." << endl; return; } memset(pszBuf, 0, sizeof(CNew)); //2. 使用 placement new CNew* pNew = new(pszBuf) CNew(123); CNew* pNewTemp = new(g_szBuf) CNew(456); //使用对象 pNew->PrintInfo(); pNewTemp->PrintInfo(); //3. 显式调用析构函数 pNew->~CNew(); pNewTemp->~CNew(); //4. 释放预定义的缓冲 if (NULL != pszBuf) { delete[] pszBuf; pszBuf = NULL; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值