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 vector
goes out of scope, or you erase
, pop_back
or do something else that removes elements from the vector, without first delete
ing 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.
It's only a memory leak if you forget to deallocate the children node when the class containing the vector's destructor is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With