how to delete a shared pointer value in vector

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-05 04:35:13

问题


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

then a vector : 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()).

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. (only the shared pointer which is in vector pointing to the dynamic memory i.e count is 1)

Thanks in advance.


回答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.

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




回答2:


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. If another shared_ptr holds a pointer to the object, the object is not deleted.

You should see the same behavior when you remove shared_ptrs from your vector.

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()


来源:https://stackoverflow.com/questions/26794750/how-to-delete-a-shared-pointer-value-in-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!