删除由两个指针引用的对象指针 [英] deleting object pointer referring by two pointers

查看:99
本文介绍了删除由两个指针引用的对象指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象要说.

ClassA *obj1 = new ClassA;

ClassA *ptr1 = obj1;
ClassA *ptr2 = obj1;

当我执行delete ptr1;时,会影响ptr2吗?如果是这样,什么是正确的解决方案?

When I do delete ptr1;, will it affect ptr2? If so what can be the correct solution for this?

推荐答案

(假设obj2应该是obj1)

ClassA *x定义了一个 pointer ,它可以指向ClassA类型的对象.指针本身不是对象.

ClassA *x defines a pointer that can point to objects of type ClassA. A pointer isn't an object itself.

new ClassA分配(并构造)类型为ClassA的实际对象.

new ClassA allocates (and constructs) an actual object of type ClassA.

因此,行Class A *obj1 = new ClassA;定义了指针obj1,然后将其设置为指向类型为ClassA的新分配对象.

So the line Class A *obj1 = new ClassA; defines a pointer obj1 and then sets it to point to a newly allocated object of type ClassA.

Class A *ptr1 = obj1;行定义了一个指针ptr1,然后将其设置为指向obj1所指向的同一对象,即我们刚刚创建的ClassA对象.

The line Class A *ptr1 = obj1; defines a pointer ptr1 and then sets it to point to the same thing obj1 is pointing to, that is, the ClassA object we just created.

Class A *ptr2 = obj1;行之后,我们有三个指针(obj1ptr1ptr2)都指向同一对象.

After the line Class A *ptr2 = obj1;, we have three pointers (obj1, ptr1, ptr2) all pointing to the same object.

如果我们执行delete ptr1;(或等效地,delete obj1;delete ptr2;),则会销毁指向对象的对象.执行完此操作后,指向该对象的任何指针都将变为无效(这将回答您的第一个问题:是的,它将影响ptr2,因为从某种意义上讲,ptr2之后将不再指向有效对象).

If we do delete ptr1; (or equivalently, delete obj1; or delete ptr2;), we destroy the pointed to object. After doing this, any pointer that was pointing to the object is made invalid (which answers your first question: yes, it will affect ptr2 in the sense that ptr2 won't be pointing to a valid object afterwards).

正确的解决方案取决于您要实现的目标:

The correct solution depends on what you're trying to achieve:

  • 如果要对象的两个副本,并假设ClassA具有副本构造函数,请执行ClassA *ptr2 = new ClassA(*obj1);.完成后,您将需要分别delete这个新对象!
  • 如果您想要两个指向同一个对象的指针,请考虑使用类似boost::shared_ptr的方法(用Google搜索)
  • If you want two copies of the object, assuming ClassA has a copy constructor, do ClassA *ptr2 = new ClassA(*obj1);. You will need to delete this new object separately when you are done with it!
  • If you want two pointers to the same object, consider using something like boost::shared_ptr (google it)

嗯,这么简单的q + a就是很多文字.嗯.

Hmm, that's alot of text for such a simple q+a. Ah well.

这篇关于删除由两个指针引用的对象指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆