我已经使用c++有一段时间了,我一直在想这个新的关键字。简单地说,我是否应该使用它?
使用new关键字…
MyClass* myClass = new MyClass();
myClass->MyField = "Hello world!";
没有new关键字…
MyClass myClass;
myClass.MyField = "Hello world!";
从实现的角度来看,它们似乎并没有什么不同(但我确信它们确实不同)……然而,我的主要语言是c#,当然第一个方法是我所习惯的。
困难在于方法1很难与std c++类一起使用。
我应该用哪种方法?
更新1:
最近,我为一个超出作用域(即从函数返回)的大数组使用了用于堆内存(或自由存储)的new关键字。在我使用堆栈之前,会导致一半的元素在作用域外损坏,切换到堆使用可以确保元素完好无损。耶!
更新2:
我的一个朋友最近告诉我,使用new关键字有一个简单的规则;每次输入new,都输入delete。
Foobar *foobar = new Foobar();
delete foobar; // TODO: Move this to the right place.
这有助于防止内存泄漏,因为您总是必须将删除放在某个地方(即当您剪切并粘贴到析构函数或其他方法时)。
如果你是用c++写的,你可能是为了性能而写的。使用new和free store要比使用堆栈慢得多(特别是在使用线程时),所以只在需要时使用它。
正如其他人所说,当你的对象需要存在于函数或对象作用域之外,对象非常大,或者当你在编译时不知道数组的大小时,你需要new。
另外,尽量避免使用delete。把你的新代码包装成智能指针。让智能指针为你调用删除。
There are some cases where a smart pointer isn't smart. Never store std::auto_ptr<> inside a STL container. It will delete the pointer too soon because of copy operations inside the container. Another case is when you have a really large STL container of pointers to objects. boost::shared_ptr<> will have a ton of speed overhead as it bumps the reference counts up and down. The better way to go in that case is to put the STL container into another object and give that object a destructor that will call delete on every pointer in the container.