简体   繁体   English

如何删除向量中的共享指针值

[英]how to delete a shared pointer value in vector

I have type defined a shared pointer as : typedef shared_ptr<Myclass> Sptr; 我已经将共享指针定义为: typedef shared_ptr<Myclass> Sptr;

then a vector : vector<Sptr> vectr ; 然后是一个向量: vector<Sptr> vectr ;

now I have stored several shared pointers in a vector, each is pointing to a dynamically allocated memory. 现在,我在向量中存储了几个共享指针,每个共享指针都指向动态分配的内存。

now I want to delete particular element(child) in a vector(children.begin() to children.end()). 现在我想删除向量中的特定element(child)(children.begin()到children.end())。

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

Now children.erase(it), will this delete the memory which is dynamically allocated and pointed by the pointer inside shared pointer. 现在children.erase(it)将删除共享指针中的指针动态分配和指向的内存。 (only the shared pointer which is in vector pointing to the dynamic memory ie count is 1) (只有共享指针在向量中指向动态内存,即计数为1)

Thanks in advance. 提前致谢。

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. 这将释放共享指针所拥有的对象的关联内存。

If you know the reference count is one... BUT... 如果您知道参考计数是一个...但是...

...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 如果您有足够的知识...并且此向量是“拥有的”集合,请考虑其他替代方法,例如std :: unique_ptr

When a shared_ptr is deleted, it deletes the object to which it holds a pointer if and only if that's the last shapred_ptr that holds a pointer to the object. 删除shared_ptr ,当且仅当那是持有指向该对象的指针的最后一个shapred_ptr ,它才会删除持有该指针的对象。 If another shared_ptr holds a pointer to the object, the object is not deleted. 如果另一个shared_ptr持有指向该对象的指针,则不会删除该对象。

You should see the same behavior when you remove shared_ptr s from your vector . vector删除shared_ptr时,应该会看到相同的行为。

Example code: 示例代码:

#include <iostream>
#include <vector>
#include <memory>

struct A
{
   ~A() {std::cout << "Came to ~A()\n";}
};

int main(int argc, char** argv)
{
   std::shared_ptr<A> ptr1(new A());
   std::shared_ptr<A> ptr2(new A());

   {
      std::cout << "In the nested scope\n"; 
      std::vector<std::shared_ptr<A>> ptrList;
      ptrList.push_back(ptr1);
      ptrList.push_back(ptr2);
   }

   std::cout << "Out of the nested scope\n"; 

   return 0;
}

OUtput: 输出:

In the nested scope
Out of the nested scope
Came to ~A()
Came to ~A()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM