Reputation: 1171
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.
Upvotes: 1
Views: 10305
Reputation: 206567
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_ptr
s 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()
Upvotes: 2
Reputation: 33607
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
Upvotes: 3