如何删除向量中的共享指针值 [英] how to delete a shared pointer value in vector

查看:74
本文介绍了如何删除向量中的共享指针值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将共享指针类型定义为:typedef shared_ptrSptr;

I have type defined a shared pointer as : typedef shared_ptr<Myclass> Sptr;

然后是一个向量:vector向量;

现在我已经在一个向量中存储了几个共享指针,每个指针都指向一个动态分配的内存.

now I have stored several shared pointers in a vector, each is pointing to a dynamically allocated memory.

现在我想删除向量中的特定元素(子)(children.begin() 到 children.end()).

now I want to delete particular element(child) in a vector(children.begin() to children.end()).

ItemList::iterator it = find(children.begin(), children.end(), child);
if (it != children.end())
{
    //delete it;
    it = children.erase(it);
}    

现在children.erase(it),这是否会删除共享指针内的指针动态分配和指向的内存.(只有指向动态内存的向量中的共享指针,即计数为1)

Now children.erase(it), will this delete the memory which is dynamically allocated and pointed by the pointer inside shared pointer. (only the shared pointer which is in vector pointing to the dynamic memory i.e count is 1)

提前致谢.

推荐答案

是的.如果共享指针的唯一实例是向量中的实例,则将其从向量中擦除将导致该共享指针实例的析构函数运行.这将为共享指针拥有的对象释放关联内存.

Yes. If the only instance of a shared pointer is the instance in the vector, then erasing it out of the vector will lead to the destructor for that shared pointer instance running. And that will free the associated memory for the object the shared pointer owns.

如果你知道引用计数是一......但是......

...使用共享指针的原因之一正是您不知道什么时候是最后一个实例.如果你有那么多的知识......并且这个向量是拥有"集合,那么考虑像 std::unique_ptr

...one of the reasons to use a shared pointer is precisely that you don't know when something is the last instance. If you have that much knowledge...and this vector is the "owning" collection, then consider alternatives like std::unique_ptr

这篇关于如何删除向量中的共享指针值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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