指针和指针在C ++中的集合。如何正确删除 [英] Pointers and collection of pointers in C++. How to properly delete
问题描述
这是一个新的问题,但我已经用C指针的alwasy怀疑。这是情况。
This is a newbe question but I have alwasy doubts with pointers in C++. This is the situation.
我有一个类A作为类B的指针的集合(实际上是一个向量)。同一个类A有另一个指针集合最后,类B的对象还有一个指向类C的指针的集合,指向类A指向的相同实例。
I have a class A which as a collection (a vector actually) of pointers of class B. This same class A has another collection of pointers to class C. Finally the objects of class B have also a collection to pointers to class C which point to the same instances the class A points to.
我的问题是,如果我在类B中删除了类C类型指针的成员,类A中指向类C的删除实例的指针发生了什么?这种情况如何处理?
My question is, if I delete a member of class-C-type pointer in class B, what happens to the pointer in class A that points to the deleted instance of class C? How this situation has to be treated?
非常感谢!
Julen。
推荐答案
我的理解:
A
- vector<B*>
- vector<C*>
B
- vector<C*>
从B中删除所有的C *。
From within B you are deleting all of the C*.
您需要单独删除每个内存地址,但最多只能删除一次。
You need to delete each memory address separately, but only at most once.
任何指向已删除地址的指针仍然拥有相同的地址,如果您使用它,它只会产生未定义的行为。
Any pointer to a deleted address is still holding the same address, it just produces undefined behavior if you use it.
因此,请务必不要从已删除的A中重新删除B *,并确保在删除之后不要使用它们。
So be sure not to re-delete the B* from A that you already deleted, and be sure not to use them after they are deleted.
您可能想重新考虑您的层次结构/设计。
You may want to re-consider your hierarchy/design though.
或考虑使用 boost :: shared_ptr 如果你需要以这种方式存储的东西。实际上,只要你存储指针的集合,你应该使用boost :: shared_ptr。如果你使用boost :: shared_ptr,你不会删除,你不需要担心使其他指针无效。
Or consider using boost::shared_ptr if you need to store things in this way. Actually anytime you're storing a collection of pointers you should probably be using boost::shared_ptr. If you are using boost::shared_ptr you don't delete and you don't need to worry about invalidating the other pointers.
这篇关于指针和指针在C ++中的集合。如何正确删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!