Is push_back memory leak a pointer to a pointer vector?

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 beyond the scope, right?

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

+6
source share
5 answers

This is not a leak ... yet. However, if vector goes out of scope, or you erase , pop_back or do something else that removes elements from the vector, without the first delete element that you delete, you will have a leak on your hands.

The right way to do this is to switch from using 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.

+12
source

This is only a memory leak if you forget to free the children of the node when the class containing the vector destructor is called.

+2
source

This is not a memory leak. You still have a pointer to a vector, and you can free up memory if necessary.

+1
source

When a vector goes out of scope, it does not destroy the object with the pointer. It destroys a pointer that does nothing.

Your code created this object via new . Your code is responsible for deleting this object. If you do not, you have a leak. If you do this earlier, that is, before removing the pointer from the vector, you have even more problems.

+1
source

Assuming that children is a member of the class, you simply just delete all the elements in the vector in the class deconstructor.

 struct Foo{}; class Bar { public: Bar(){}; ~Bar() { for( vector<Foo*>::iterator it = children.begin(); it != children.end(); ++it ) { SAFE_DELETE( (*it) ); //use your own macro/template or use delete if you don't have one delete (*it); (*it) = NULL; } } vector<Foo*>children; } Foo* p = new Foo(); children.push_back( p ); 

If you used vector<Foo>child instead, each push_back on the vector would create a copy of the original object to be stored, but since you are using pointers, in this case no copy of the object is allocated in the new heap, a pointer pointing to the long-term object the deadline is simply saved, that is, yes, you must delete it later.

-3
source

Source: https://habr.com/ru/post/925506/


All Articles