Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a memory leak to push_back a pointer into a vector of pointers?

In my class, I have a member variable std::vector<node*> children

Does the following class member function create a memory leak?

//adds a child node
{
    node* child = new node("blah","blah","blah");
    child->Set_Parent(this);
    children.push_back(child);  //<- Is this ok?
}

The vector makes a copy of the pointer and I have two pointers to the same memory, and then the original pointer goes out of scope, right?

This may be simple and obvious, but I would just like to confirm my assumption.
thanks

like image 821
Trevor Hickey Avatar asked Sep 16 '12 05:09

Trevor Hickey


2 Answers

It's not a leak ... yet. However, if the vector goes out of scope, or you erase, pop_back or do something else that removes elements from the vector, without first deleteing the element that you're removing you'll have a leak on your hands.

The right way to do this is to change from using a vector<node *> to vector<unique_ptr<node>>. Your code will change to

//adds a child node
{
    node* child = new node("blah","blah","blah");
    child->Set_Parent(this);
    children.push_back(std::unique_ptr<node>(child));
}

Or use boost::ptr_vector<node> if you can use Boost.

like image 143
Praetorian Avatar answered Sep 20 '22 15:09

Praetorian


It's only a memory leak if you forget to deallocate the children node when the class containing the vector's destructor is called.

like image 43
Borgleader Avatar answered Sep 18 '22 15:09

Borgleader