I have the following situation:
I have class A that contains a stack member object from class B:
Class A{
B b;
}
I am using B object to redefine the behavior of the initialization and destruction of A.
Class B{
B(){cout<<"taken care of some specific context initialization"<<endl;}
~B(){cout<<"cleaning the context initialization done before"<<endl;}
}
This is working so far because ~B() is being called when b is destroyed (I guess it is done after A destructor).
This is the behavior I am looking for, but I am scared about the possibility of the compiler saying: “Hey, you are not using the object, I am going to reclaim the memory before”. I guess it should to happen, but is it possible in any compiler? I mean, is it set on the standard that you have to wait for A to be destroyed?
Thanks in advance
C++ follows an as-if behavior, meaning it is theoretically possible for
bto be destroyed before as long as the behavior of the program isn’t affected. And if it isn’t affected, it doesn’t really matter when it is destroyed.In practice though,
bwill be destroyed right after the destructor of its ownerAinstance will be destroyed.It is guaranteed by:
12.4 Destructors [class.dtor]
Note that an implementation whose observable behavior acts as-if this was happening is still standard-compliant. In your particular case, since the destructor has IO operations, it’s guaranteed that this behavior actually takes place.