更新时间:2023-02-16 22:46:09
方法一(使用new
)
Method 1 (using new
)
删除
您的对象.(如果你不删除它,你可能会造成内存泄漏)删除
它.(即您可以返回
一个您使用new
创建的对象)delete代码>d;并且它应该总是被删除,无论采用哪个控制路径,或者是否抛出异常.
delete
your object later. (If you don't delete it, you could create a memory leak)delete
it. (i.e. you could return
an object that you created using new
) delete
d; 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
指向堆栈上的对象的指针)delete
it later.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
delete
, (and the potential to cause memory leaks) you shouldn't use new
.new