new、operator new 、placement new
代码来自 www.cplusplus.com
直接上代码
#include // std::cout
#include // ::operator newstruct MyClass {int data[100];MyClass() {std::cout << "constructed [" << this << "]\n";}
};int main () {//newstd::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 newstd::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 newint 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的重载,不分配内存,在已有内存上重新构造一个对象
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
