2

On the description from http://www.cplusplus.com/reference/list/list/erase/ , I get

   This effectively reduces the container size by the number of elements removed,
which are destroyed.

Similar description for pop method.

But in my test on VS2012, the item removed is not destroyed. I'm confused about this.

This is my test code. I still can output from the memory erased by std::list, which in my opinion, is WRONG.

#include <stdio.h> 
#include <list>
using namespace std;
class test
{
public:
   int a;
   test() {a = 111;}
};
int main(void)
{
   list<test*> l;
   test* t = new test;
   l.push_back(t);
   l.erase(l.begin());
   printf("%d\n", t->a);

   return 0;
}
Robert Bean
  • 851
  • 2
  • 11
  • 21
  • perhaps you should learn the basics (meaning of pointer etc) first before going to such "advanced" features as `std::list` ? – Walter Sep 26 '13 at 08:32
  • 1
    What did you expect to happen with your bugged code? If you were expecting some kind of error message or crash then I'm afraid you are going to be very disappointed in C++. Most errors cause *Undefined Behaviour* which mean that literally anything can happen. – john Sep 26 '13 at 08:46

1 Answers1

8

The item is destroyed, that is it's destructor is called. Alas, destructor of a pointer does nothing. In particular, it does not delete the pointed object.

Remember, unlike Java and C#, C++ has value semantics for everything and pointer and references are explicit constructs that you have to always handle yourself. So destroying a pointer and deleting the pointed object are distinct actions.

If you have C++11, the std::unique_ptr is usable in list and will ensure deleting the pointed object, but it is not copyable to enforce correct memory management. If you need copying, you can use (also C++11) std::shared_ptr, which can be copied, but has some runtime overhead.

If you don't have C++11, you can use Boost.PointerContainer or boost::shared_ptr.

Of course, most of the time you shouldn't be using indirection at all in the first place. Manipulating objects by value is preferred in C++ where applicable. It notably is not applicable for polymorphic objects, but they are not that common in C++ in practice.

Community
  • 1
  • 1
Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • 2
    I would add the the better solition, in many cases, is not to use any kind of pointer at all. I know this is only test code but `list` has to be an option. – john Sep 26 '13 at 08:44