Does list::pop_front call destructor

Mar 31, 2009 at 11:17am
Hi,
Can any one give some idea whether the call to list::pop_front invokes destructor or not. As per definition given for list::pop_front on cplusplus.com site

call to list::pop_front() removes the first element in the list container, effectively reducing the list size by one.This calls the removed element's destructor. (http://www.cplusplus.com/reference/stl/list/pop_front.html)

But when I tried that, it was not invoking the destructor. Will I have to explicitely invoke the destructor

Thanks
Shiv
Mar 31, 2009 at 11:58am
Why do you say that it doesn't call the destructor?
Try this code:
1
2
3
4
5
6
struct S
{
    ~S() { cout << "Destructor Called"; }
}aValue;
list<S> li(2,aValue);
li.pop_front();


It should display "Destructor Called"
Mar 31, 2009 at 12:35pm
If you have a list of pointers-to-something then keep in mind that what is being destroyed is the pointer, which is not the same thing as destroying the object.

So to give a counterexample using Bazzy's code,

1
2
3
4
5
6
7
8
struct S
{
    ~S() { cout << "Destructor Called"; }
};

list<S*> li;
li.push_back( new S );
li.pop_front();


In this case ~S is NOT called, because what is being destroyed is an S*, not an S.
Last edited on Mar 31, 2009 at 12:35pm
Topic archived. No new replies allowed.