Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling clear() on a vector of shared_ptr. Will memory be freed?

I have a std::vector member of boost::shared_ptr to objects of class Foo inside a class. A function SetData() adds a pointer to a new object of Foo to the vector. The contructor of Foo makes an internal copy of the data pointed to by pData. Now when I call my Reset() function, will all the memory actually be freed?

class myClass()
{
 void SetData(char* pData, size_t nSize)
 {
   boost::shared_ptr<Foo> pFoo(new Foo(pData, nSize));
   mVector.push_back(pFoo);
 }

 void Reset()
 {
   mVector.clear();
 }

private:
    std::vector<boost::shared_ptr<Foo>> mVector;


};
like image 679
tzippy Avatar asked Sep 15 '25 21:09

tzippy


1 Answers

will all the memory actually be freed?

It rather depends on what you're asking. On the surface of it, yes.

The entire purpose of smart pointers is that they manage memory for you, and the entire purpose of shared pointers it that the thing they point to is automatically freed when no more shared pointers point to it.

When you clear the vector, the shared pointers it contains are destroyed, and this action automatically de-allocates any encapsulated objects with no more shared pointers referring to them.

Now, does that free all memory? Not necessarily. We have no idea what Foo does; if you didn't properly implement RAII in it, then it's possible that Foo leaks memory and the answer becomes no.

like image 182
Lightness Races in Orbit Avatar answered Sep 17 '25 10:09

Lightness Races in Orbit