Originally Posted by
micahharwell
I've been reading and understand that classes that contain dynamically allocated members will copy only the pointer to these members when using the default constructors. But I've only seen this in the context of using "new", "malloc", etc...
Are the STL containers immune to this? Or do I still need to provide my own copy and/or assignment constructor?
The default copy constructor basically invokes the copy constructor of each member, unless it's a built-in type (int, double, pointers, etc), in which case the underlying bytes are simply copied into the member. In the case of pointers that are "managed" by the object this can be disastrous, as multiple objects are then prone to "free" the object.
Code:
#include <iostream>
struct foo
{
foo( void )
{
data = new int;
}
~foo( void )
{
std::cout << "foo (" << static_cast< void* >( this ) << ") freeing data (" << data << ")" << std::endl;
delete data;
}
int* data;
};
int main( void )
{
foo a, b = a;
}
So...yes, you generally need to write your own copy constructor in such a case (or else use a "smart-pointer", or similar).