代码来自 www.cplusplus.com
直接上代码
#include <iostream> // std::cout
#include <new> // ::operator new
struct MyClass {
int data[100];
MyClass() {std::cout << "constructed [" << this << "]\n";}
};
int main () {
//new
std::cout << "1: ";
MyClass * p1 = new MyClass;
// allocates memory by calling: operator new (sizeof(MyClass))
// and then constructs an object at the newly allocated space
//调用 operator new 分配内存,然后调用构造函数生成一个对象,并返回指针
std::cout << "2: ";
MyClass * p2 = new (std::nothrow) MyClass;
// allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
// and then constructs an object at the newly allocated space
//placement new
std::cout << "3: ";
new (p2) MyClass;
// does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
// but constructs an object at p2
//不分配内存,在p2指向的内存上重新构造一个对象
//operator new
// Notice though that calling this function directly does not construct an object:
std::cout << "4: ";
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
// allocates memory by calling: operator new (sizeof(MyClass))
// but does not call MyClass's constructor
//分配内存,但是不调用构造函数
//placement new
int a=100;
cout<<"before:"<<a<<endl;
int *ptr=new (&a) int(50);
cout<<"after:"<<a<<endl;
delete p1;
delete p2;
delete p3;
return 0;
}
代码结果
1: constructed [0x8f0f70]
2: constructed [0x8f23a8]
3: constructed [0x8f23a8]
4:
before:100
after:50
总结
new
调用operator new
分配内存,然后调用构造函数,最后返回指针operator new
只分配内存,不调用构造函数placement new
是operator new
的重载,不分配内存,在已有内存上重新构造一个对象