objects_list.push_back(new ObjectA(this));
This can leak memory. Let's see what happens when we break it down:
new ObjectA(this)
is allocated
push_back
is then called
However, push_back
can throw and if it does, your new ObjectA
is leaked.
The auto_ptr
code you showed us solves this problem: if push_back
throws then the pointer is still owned by auto_ptr
and no leak happens.
The real solution would be to store smart pointers directly in the container instead of naked pointers (because naked pointers in containers are a headache when it comes to ensuring the objects are correctly deleted).
Unfortunately with C++03 (which is where auto_ptr
comes from, it's been deprecated in C++11) this is not possible to store auto_ptr
in containers (the pattern is badly broken). One could store boost::shared_ptr
in containers, or switch to C++11 and store either unique_ptr
or shared_ptr
.