如何使用删除与由两个指针指向的变量? [英] How to use delete with a variable pointed to by two pointers?
问题描述
假设我有一个以 new
声明的假设指针:
Let say I have a hypothetical pointer declared with new
like so:
int* hypothetical_pointer = new int;
并创建另一个具有相同值的假设指针:
and create another hypothetical pointer, with the same value:
int* another_hypothetical_pointer = hypothetical_pointer;
如果我要删除这些,指针,还是只有一个明确声明为new?或者我可以删除任何一个指针吗?
If I were to go about deleting these, which were declared with new, would I have to delete both pointers, or only the one explicitly declared with new? Or could I delete either pointer?
推荐答案
delete
对象由指针指向。
当你 delete hypothetical_pointer时,就会有一个指针指向这个对象。 ;
,不能使用 hypothetical_pointer
或 another_hypothetical_pointer
,因为它们都不指向有效对象。
After you delete hypothetical_pointer;
, you cannot use hypothetical_pointer
or another_hypothetical_pointer
because neither of them points to a valid object.
如果你需要有多个指针指向同一个对象,你应该使用共享所有权智能指针,例如 shared_ptr
,以确保对象不被过早地销毁,并且它被精确地销毁一次。 C ++中的手动资源管理充满危险,应该避免。
If you need to have multiple pointers pointing to the same object, you should use a shared-ownership smart pointer, like shared_ptr
, to ensure that the object is not destroyed prematurely and that it is destroyed exactly once. Manual resource management in C++ is fraught with peril and should be avoided.
这篇关于如何使用删除与由两个指针指向的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!