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
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 .
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.
The push_back() function is used to insert an element at the end of a vector.
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.
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