我有两门课,比如 A 和 A。 B. B 类有自己的析构函数。在 A 类中,我有一个指向 B 类对象的指针向量。该向量如下:
vector<B*> vect;
在 A 类的析构函数中,如何检索内存?如果我循环遍历向量,是否检索每个对象并对每个检索到的对象使用删除?我在析构函数中尝试了这一点,但它出现了段错误。
非常欢迎任何解决此问题的帮助。很抱歉,我无法发布代码。
I have 2 classes, say A & B. Class B has a destructor of its own. Within class A, I have a vector of pointers to objects of class B. The vector is as follows:
vector<B*> vect;
In the destructor for class A, how do I retrieve memory? If I cycle through the vector, do I retrieve each object and use delete on every retrieved object? I tried that out in the destructor, but it segfaults.
Any help in solving this problem is most welcome. I am sorry but I cannot post the code.
发布评论
评论(6)
如果 A 拥有
vect
所指向的内容,那么它应该能够删除
vect 中的每一项。如果这样做时出现段错误,那么您的代码中某个地方就有错误。不过,一般来说,您最好使用智能指针。 Boost 的 ptr_vector (Boost.Pointer Container 是为您的具体示例而设计的,但是一个简单的
std::vector > 也可以工作(尽管有更多的开销和更尴尬的语法)。
If A owns the things pointed to by
vect
, then it should be able todelete
each item withinvect
. If it segfaults while doing so, then you have a bug somewhere in your code.In general, though, you're better off using smart pointers. Boost's ptr_vector (part of Boost.Pointer Container is designed for your specific example, but a simple
std::vector<std::tr1::shared_ptr<B> >
will also work (albeit with more overhead and a more awkward syntax).其他一些帖子指出,最好使用智能指针而不是指针。如果出于任何原因必须使用指针,您应该首先在循环中删除它们。
编辑:
如果你的程序在析构函数中出现段错误,那么你的代码就是错误的。也许您可以按地址将堆栈元素放入向量中,但要删除对象,它必须位于堆上。
这工作没有问题。
Some other posts pointed out that you're better of using smart pointers instead of pointers. If you have to use pointer for any reason whatsoever you should delete them in a loop first.
edit:
If your program segfault in the destructor then your code is wrong. Maybe you put stack element by adress in the vector, but to delete an object it has to be on the heap.
This works without problem.
是的,如果
B*
类型的项指向堆上分配的对象,那么对于每个项,您应该对其调用delete。Yes if the items of type
B*
point to objects allocated on the heap, then for each item you should call delete on it.是的,您将循环向量并删除每个项目。问题是你忘记了第 42 行的毛巾操作员。
Yes, you would loop the vector and delete each item. The problem is that you forgot the towel operator on line 42.
当您需要管理指针的生命周期时,您希望避免将指针存储在容器中。
如果这是一个真正的所有者并且保证是最后一个清理那么我会选择
如果你有不同的引用和可能重叠的生命周期那么shared_ptr会更好(std::tr1或boost取决于编译器)
You want to avoid storing pointers in containers when you need to manage their lifetime.
If this is the one true owner and is guaranteed to be last to cleanup then I'd go with
If you have different references and lifetimes that may overlap then shared_ptr would be better (std::tr1 or boost depending on compiler)
根据您的描述,听起来 A 类的 vect 成员应该拥有 B* 指向的数据的终生所有权。
我建议将该声明更改为
EDIT: Replaced auto_ptr with std::tr1::shared_ptr
From your description it sounds like your vect member of class A should have lifetime ownership of the data pointed by the B*.
I would recommend just changing that declaration to
EDIT: replaced auto_ptr with std::tr1::shared_ptr