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
It’s not a leak … yet. However, if the
vectorgoes out of scope, or youerase,pop_backor do something else that removes elements from the vector, without firstdeleteing 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 *>tovector<unique_ptr<node>>. Your code will change toOr use
boost::ptr_vector<node>if you can use Boost.