700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > new operator new placement new

new operator new placement new

时间:2024-02-19 01:45:04

相关推荐

new operator new  placement new

代码来自

直接上代码

#include <iostream>// std::cout#include <new>// ::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:100after:50

总结
new调用operator new分配内存,然后调用构造函数,最后返回指针operator new只分配内存,不调用构造函数placement newoperator new的重载,不分配内存,在已有内存上重新构造一个对象

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。