-
Is this a memory leak?
I need someone with more of a clue than I have to tell me if this code snippet shows a memory leak.
Code:
std::list< MyClass > myList;
void myFunc ( std::list< MyClass > &myList, int numObjects )
{
MyClass * myObj;
for ( int i = 0; i < numObjects; ++i )
{
myObj = new MyClass();
myList.push_back( *myObj );
}
}
I have searched online trying to find out if the STL list makes a copy of the object when it's pushed onto the list, which in my mind would definitely cause a leak, or if it will push the actual object.
I know that I can change the type of data in the list to pointers to avoid this, but I want to know what is going on in this example.
Many thanks in advance for your help!
-
Yes, that is a memory leak.
Yes, it pushes a copy (even if it didn't push a copy, you never delete the pointer anywhere).
You don't need to use new in your example, so don't and you won't have to worry about memory. If in your actual code, you must use new, then you should store a shared_ptr or a raw pointer in the list. If you use a raw pointer, just remember to delete the object whenever you erase from or clear the list(assuming no other part of your code owns the object as well).
-
It makes a copy to my knowledge. When you push back you are passing a const reference to the object. Which when you do that it will call a copy constructor to copy over the values. So yes it will be a memory leak.
-
Note that it is not the const reference passing that makes the copy (since it is a reference), but other code inside the push_back that copies the object.
-
this will prevent the memory leak
Code:
void myFunc ( std::list< MyClass > &myList, int numObjects )
{
for ( int i = 0; i < numObjects; ++i )
{
MyClass myObj;
myList.push_back( myObj );
}
}
-
Thanks for the help. I always seem to do things the round-a-bout hard way ( with errors apparently)!