Re: why it seems that std::list::erase() doesnt free objects in a list, if the latter holds pointers to them?

From: Rob Williscroft (rtw_at_freenet.co.uk)
Date: 04/11/04


Date: 11 Apr 2004 15:08:57 GMT

jimjim wrote in news:Y3dec.1164$FT7.11504891@news-text.cableinet.net in
comp.lang.c++:

> I would appreciate helping me understand why erase doesnt delete the
> object when I store a pointer to the object.
>
> Thanks in advance
>
>

#include <iostream>
#include <ostream>
#include <list>

using namespace std;

class X
{
public:
  X(){ cout << "X constructor\n"; }
  ~X() { cout << "X destructor\n"; }
  X( X const & ) { cout << "X copy constructor\n"; }

};

int main()
{
  X x;
  list<X>lists;
  lists.push_back(x);
  lists.erase(lists.begin());
}

output:

            X constructor
            X copy constructor
            X destructor
            X destructor

Note 2 constructors followed by 2 destructors:

The 1st ctor is for local 'x'.
The 2nd ctor is for the *copy* that is pushed into 'lists'.
The first dtor is for the X erased by erase( lists.begin() ).
The last dtor is for local 'x'.

Rob.

-- 
http://www.victim-prime.dsl.pipex.com/


Relevant Pages

  • Re: The difference between 0 and NULL?
    ... I noticed there existed only one ctor for the class and it was ... It's a no argument ctor that initializes 3 variables in ... I noticed that the pointer was being ... Perhaps your first compile was bad ...
    (comp.unix.programmer)
  • RE: ECMA Wrong - Class and Object Initialization Rules - Help!
    ... > An instance of a class can be created only if the constructor of the class' ... the this pointer is initialized. ... In my example, the .ctor of Object is not invoked at all - so, strictly ... the two .ctor-s invoke each other. ...
    (microsoft.public.dotnet.framework.clr)
  • Re: The difference between 0 and NULL?
    ... > program (the calls to printf() notwithstanding) and ModemObject is a ... I noticed there existed only one ctor for the class and it was ... It's a no argument ctor that initializes 3 variables in ... I noticed that the pointer was being ...
    (comp.unix.programmer)
  • Re: basic_string ctor
    ... Duane Hebert wrote: ... pass a null into a basic_string ctor? ... Or, more precisely, is it legal C++ to pass a null pointer into a basic_string parameter on a method? ... In my opinion the cost of the extra ifwould have been well worth ...
    (microsoft.public.vc.stl)