Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: is push_back(new Object()) a memory leak?

Is the following C++ code a memory leak?

list.push_back(new String("hi"));

As I understand it, push_back from any std collection/container always makes a copy. So if the new string is copied, nothing can ever delete the new'd string right? since there is no reference to it after the push_back...

Am I correct or wrong here?

Thanks.

Jbu

edit: I think I am wrong, since new will return a pointer...we'll always have the pointer to be able to delete the new String

like image 464
jbu Avatar asked Nov 24 '10 20:11

jbu


People also ask

Does Push_back make a deep copy?

It does not make deep copies, since cv::Mat 's are shared pointers. You have to use clone() or similar when adding to the vector images .

Does Push_back copy or move?

When inserted using the push_back, the new element is copy-or-move-constructed. The insertion could be inefficient if the passed argument to the push_back is a temporary because the temporary is constructed, copied/moved, and destroyed.

What does Push_back mean?

The push_back() function is used to insert an element at the end of a vector.


1 Answers

Yes, but not for the reason you think.

Depending on how list is defined and initialized, push_back might throw an exception. If it does, the pointer returned from new is lost, and can never be freed.

But assuming push_back returns successfully, it stores a copy of the pointer returned by new, and so we can free the memory later by calling delete on that copy, so no memory is leaked as long as you do call delete properly.

like image 118
jalf Avatar answered Sep 22 '22 16:09

jalf