myVector.erase(myPtr)删除myPtr指向的对象吗? [英] Does myVector.erase(myPtr) delete the object pointed by myPtr?

查看:157
本文介绍了myVector.erase(myPtr)删除myPtr指向的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码,

Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);

我是否创建了内存泄漏?
我猜是这样,但是擦除这个词给出了删除它的感觉。

Did I create a memory leak? I guess so, but the word erase gives the feeling that it is deleting it.

写这个,我想知道在STL向量中放置指针是否是错误的。

Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you think?

推荐答案

是的,您创建了一个内存泄漏。 std :: vector和其他容器只会删除指针,它们不会释放指针指向的内存。

Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.

将指针放入标准并不奇怪库容器。然而,问题是,您必须跟踪删除它从容器中删除它。一个更好,但简单的方法来做上述,是使用boost :: shared_ptr:

It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the container. A better, yet simple, way to do the above, is to use boost::shared_ptr:

{ 
    boost::shared_ptr<foo> f(new foo);

    std::vector< boost::shared_ptr<foo> > v;
    v.push_back(f);
    v.erase(v.begin());
} /* if the last copy of foo goes out of scope, the memory is automatically freed */


$ b b

下一个C ++标准(通常称为C ++ 1x和C ++ 0x)将包括 std :: shared_ptr 。在那里,你还可以使用 std :: unique_ptr< T> ,这更快,因为它不允许复制。使用c ++ 0x中的容器使用 std :: unique_ptr 与boost中的 ptr_container 库类似。

The next C++ standard (called C++1x and C++0x commonly) will include std::shared_ptr. There, you will also be able to use std::unique_ptr<T> which is faster, as it doesn't allow copying. Using std::unique_ptr with containers in c++0x is similar to the ptr_container library in boost.

这篇关于myVector.erase(myPtr)删除myPtr指向的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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