// 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; } }
在固定位置new一个对象源代码
最新推荐文章于 2023-02-07 16:14:24 发布