且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该在 C++ 中使用 new 关键字?

更新时间:2023-02-16 22:46:09

方法一(使用new)

Method 1 (using new)

  • 免费存储上的对象分配内存(这通常与相同)
  • 要求您稍后明确删除您的对象.(如果你不删除它,你可能会造成内存泄漏)
  • 内存保持分配状态,直到您删除它.(即您可以返回一个您使用new创建的对象)
  • 问题中的示例将泄漏内存,除非指针是delete代码>d;并且它应该总是被删除,无论采用哪个控制路径,或者是否抛出异常.
  • Allocates memory for the object on the free store (This is frequently the same thing as the heap)
  • Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak)
  • Memory stays allocated until you delete it. (i.e. you could return an object that you created using new)
  • The example in the question will leak memory unless the pointer is deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.

方法二(不使用new)

Method 2 (not using new)

  • 堆栈上的对象分配内存(所有局部变量所在的位置) 堆栈可用的内存通常较少;如果分配的对象过多,则会面临堆栈溢出的风险.
  • 您以后无需删除它.
  • 超出范围时不再分配内存.(即,您不应该return 指向堆栈上的对象的指针)
  • Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
  • You won't need to delete it later.
  • Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't return a pointer to an object on the stack)

至于使用哪个;考虑到上述限制,您可以选择最适合您的方法.

As far as which one to use; you choose the method that works best for you, given the above constraints.

一些简单的案例:

  • 如果您不想担心调用 delete,(以及可能导致 内存泄漏) 你不应该使用 new.
  • 如果你想从一个函数返回一个指向你的对象的指针,你必须使用 new
  • If you don't want to worry about calling delete, (and the potential to cause memory leaks) you shouldn't use new.
  • If you'd like to return a pointer to your object from a function, you must use new