内存分配与对象构造的分开

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

class T
{
public:
T() {cout
<< "construct" << endl;}
~T() {cout << "destruct" << endl;}
};

int main()
{
T
*t1;
//operator new函数:获取未构造内存
t1 = static_cast<T *>(operator new(sizeof(T)));
//定位new表达式:在特定的、预分配的内存地址构造一个对象
//new (place_address) tpye
//new (place_address) type (initializer-list)
new (t1) T;
//对于使用定位new表达式构造对象的程序,显式调用析构函数
t1->~T();
//operator delete函数:释放指定内存,不会运行析构函数
operator delete(t1);

allocator
<T> at;
T
*t2, t3;
t2
= at.allocate(sizeof(T));
at.construct(t2, t3);
at.destroy(t2);
at.deallocate(t2,
sizeof(T));
return 0;
}

 

posted @ 2010-10-08 21:00  penink  阅读(153)  评论(0)    收藏  举报