Destructor query

A

Andy

As I understand it, if you have object1 which has object2 as a member, when
the outer object (object1) is deleted, the destructor of the inner object
(object2) is called BEFORE the destructor of the outer object.

But, while the destructor of object1 is executing, has object2 actually been
freed?

I have seen some code where an outer object contains a smart pointer member.
In the destructor of the outer object a call is made to a method in the
object pointed-to by the smart pointer. I would have thought that by the
time the outer object's destructor is called ALL of its member objects (or
objects pointed-to by smart pointers) would no longer exist, so trying to
call a method like this would cause a memory violation. And yet the program
works OK.
 
V

Victor Bazarov

Andy said:
As I understand it, if you have object1 which has object2 as a member, when
the outer object (object1) is deleted, the destructor of the inner object
(object2) is called BEFORE the destructor of the outer object.

Incorrect. Members are destroyed after the destructor for the "outer"
object has finished. Just try this:

#include <iostream>
struct A {
~A() { std::cout << "~A"; }
};
struct B {
A a;
~B() { std::cout << "~B"; }
};
int main() {
B b;
}
But, while the destructor of object1 is executing, has object2 actually been

No.

I have seen some code where an outer object contains a smart pointer member.
In the destructor of the outer object a call is made to a method in the
object pointed-to by the smart pointer.

That should be OK.
I would have thought that by the
time the outer object's destructor is called ALL of its member objects (or
objects pointed-to by smart pointers) would no longer exist, so trying to
call a method like this would cause a memory violation. And yet the program
works OK.

As it should.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,413
Latest member
KeiraLight

Latest Threads

Top