Seems its easy question, but I am doubt. Will operator delete destroy all Object‘s elements when I call delete list for non empty list created with operator new? Sure it will, but I need confirmation. As you see Object have constructor, but without distributor.
Code:
std::list<Object>* ptr_listObjects = new std::list<Object>();
OtherObject* ptr_null = NULL;
ptr_listObjects->push_back ( Object( ptr_null, 'A') );
ptr_listObjects->push_back ( Object( ptr_null, 'A') );
ptr_listObjects->push_back ( Object( ptr_null, 'A') );
ptr_listObjects->push_back ( Object( ptr_null, 'A') );
ptr_listObjects->push_back ( Object( ptr_null, 'A') );
ptr_listObjects->push_back ( Object( ptr_null, 'A') );
delete ptr_listObjects; // no any possible memory leaks? (Object does not use `new` operator)
class Object
{
public:
Object( OtherObject* ptr_other, char xxx):
ptr_OtherObject(ptr_other),
charflag(xxx)
{}
OtherObject* ptr_OtherObject;
char charflag;
};
The
std::listdestructor will run and so will the destructor of it’s elements. That said, why are you allocating a container dynamically to begin with? You’re making it impossible for the container to manage memory for you. Let it do its job; allocate the list with automatic storage duration.As an aside,
Objectdoes have a destructor, the compiler generates an empty one for you. There’s nothing to clean up though, so it doesn’t do anything. Also, it is clear from the class design that instances ofObjectdo not own the pointer it takes in its constructor, so make sure to never deallocate it unless you change your design significantly.