BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #47050同步于 2010/11/29
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

关于operator new的用法,及由此想到的基本概念问题

hman
2010/11/29镜像同步4 回复
学了这么就c++,还是头一次知道这个概念。 汗颜。 先上一段网上的代码,和自己的改动 #include <iostream> using namespace std; // operator new example #include <iostream> #include <new> using namespace std; class myclass { public: myclass() {cout <<"myclass constructed\n";} ~myclass(){cout <<"myclass destructed\n";} }; int main () { int * p1 = new int; // same as: // int * p1 = (int*) operator new (sizeof(int)); int * p2 = new (nothrow) int; // same as: // int * p2 = (int*) operator new (sizeof(int),nothrow); myclass * p3 = (myclass*) operator new (sizeof(myclass)); // (!) not the same as: // myclass * p3 = new myclass; // (constructor not called by function call, even for non-POD types) new (p3) myclass; // calls constructor // same as: the same as?, constructor is not called // operator new (sizeof(myclass),p3); delete p3; // same as: // p3->~myclass(); // operator delete(p3); // myclass obj; myclass *pobj = new myclass; pobj->~myclass(); return 0; } 1。 这两句话 myclass * p3 = (myclass*) operator new (sizeof(myclass)); new (p3) myclass; 其实就是等同于, p3 = new myclass; 2. 这句是我写的 myclass *pobj = new myclass; pobj->~myclass(); 问题是pobj分配的内存delete了么?
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
hman机器人#1 · 2010/11/29
而且还有个疑问啊,好久不用new了。 我使用了new,构造一个新的obj,不用delete的话,这个obj是永远不会被析构的吧。 就算程序退出? 我运行的例子里面如果不用delete,destruct就不会被打印。
hman机器人#2 · 2010/11/29
嗯,然后为什么要多出这个operator new? 有什么好处呢?
giveup机器人#3 · 2010/11/30
多了operator new就是为了在内存分配时调用构造函数吧,malloc是不会调用构造函数而直接进行内存分配的,构造函数可以做一些出了类内存分配以外的事情,比如类中如果有指针成员,你可以在构造函数中对其进行内存分配,delete同理
giveup机器人#4 · 2010/11/30
【 在 hman 的大作中提到: 】 : 而且还有个疑问啊,好久不用new了。 : 我使用了new,构造一个新的obj,不用delete的话,这个obj是永远不会被析构的吧。 : 就算程序退出? 我运行的例子里面如果不用delete,destruct就不会被打印。 : ................... 这样不会调用析构函数,而是直接进行内存释放吧