我已经使用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.
如果变量只在单个函数的上下文中使用,那么最好使用堆栈变量,即选项2。正如其他人所说,您不必管理堆栈变量的生命周期——它们是自动构造和销毁的。而且,相比之下,在堆上分配/释放变量的速度较慢。如果函数被足够频繁地调用,使用堆栈变量而不是堆变量,您将看到巨大的性能改进。
也就是说,在一些明显的实例中,堆栈变量是不够的。
If the stack variable has a large memory footprint, then you run the risk of overflowing the stack. By default, the stack size of each thread is 1 MB on Windows. It is unlikely that you'll create a stack variable that is 1 MB in size, but you have to keep in mind that stack utilization is cumulative. If your function calls a function which calls another function which calls another function which..., the stack variables in all of these functions take up space on the same stack. Recursive functions can run into this problem quickly, depending on how deep the recursion is. If this is a problem, you can increase the size of the stack (not recommended) or allocate the variable on the heap using the new operator (recommended).
另一种更可能的情况是,您的变量需要“生存”在函数的作用域之外。在这种情况下,可以在堆上分配变量,以便在任何给定函数的作用域之外都可以访问它。
如果你是用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.