J
jimjim
Hello,
Consider the following:
class X{
public:
X(){ cout << "X constructor\n"; }
~X() { cout << "X destructor\n"; }
};
int main(){
X x;
list<X>lists;
lists.push_back(x);
lists.erase(lists.begin());
}
the output is:
X constructor //the constructor is called with the statement X x;
X destructor //the destructor is called with the statement
lists.erase(lists.begin()) (??)
X destructor
1. Above, why is the destructor called twice?
2. Does std::list::erase( ) delete both the x object and the Node object in
the list? Should I assume that the Node object in the list holds the object
as a whole as data, or just a pointer to it? Can you please answer with
reference to the implementation of std::list (near which line in the source
code should I look at)?
consider the following changes to main:
int main(){
X *x = new X();
list<X*>lists;
lists.push_back(x);
lists.erase(lists.begin());
}
the output is:
X constructor
3.Why doesn't (or seems that doesn't) lists.erase(lists.begin()) delete the
*x object ? ((I need to use delete (*i) to explicitly free the actual
object))
4. Should I assume that only the Node object in the list is deleted but not
the *x object? Why does this happen? Again, can you please expain with
reference to the implementation of std::list?
Thank you in advance for your help.
Consider the following:
class X{
public:
X(){ cout << "X constructor\n"; }
~X() { cout << "X destructor\n"; }
};
int main(){
X x;
list<X>lists;
lists.push_back(x);
lists.erase(lists.begin());
}
the output is:
X constructor //the constructor is called with the statement X x;
X destructor //the destructor is called with the statement
lists.erase(lists.begin()) (??)
X destructor
1. Above, why is the destructor called twice?
2. Does std::list::erase( ) delete both the x object and the Node object in
the list? Should I assume that the Node object in the list holds the object
as a whole as data, or just a pointer to it? Can you please answer with
reference to the implementation of std::list (near which line in the source
code should I look at)?
consider the following changes to main:
int main(){
X *x = new X();
list<X*>lists;
lists.push_back(x);
lists.erase(lists.begin());
}
the output is:
X constructor
3.Why doesn't (or seems that doesn't) lists.erase(lists.begin()) delete the
*x object ? ((I need to use delete (*i) to explicitly free the actual
object))
4. Should I assume that only the Node object in the list is deleted but not
the *x object? Why does this happen? Again, can you please expain with
reference to the implementation of std::list?
Thank you in advance for your help.