Is there any way to call a field destructor before the class destructor?
Suppose I have 2 classes Small and Big, and Big contains an instance of Small as its field as such:
class Small
{
public:
~Small() {std::cout << "Small destructor" << std::endl;}
};
class Big
{
public:
~Big() {std::cout << "Big destructor" << std::endl;}
private:
Small small;
};
int main()
{
Big big;
}
This, of course, calls the big destructor before the small destructor:
Big destructor
Small destructor
I need the Small destructor to be called before the Big destructor since it does some cleanup necessary for the Big destructor.
I could:
- call the
small.~Small()destructor explicitly. -> This, however, calls theSmalldestructor twice: once explicitly, and once after theBigdestructor has been executed. - have a
Small*as the field and calldelete small;in theBigdestructor
I am aware that I can have a function in the Small class that does the cleanup and call it in the Big destructor, but I was wondering if there was a way to inverse the destructor order.
Is there any better way to do this?
Well, I don't know why you want to keep on with this flawing design, but you can solve the problem described in your first bullet using placement new.
It follows a minimal, working example:
You don't have anymore a variable of type
Small, but with something like thesmallmember function in the example you can easily work around it.The idea is that you reserve enough space to construct in-place a
Smalland then you can invoke its destructor explicitly as you did. It won't be called twice, for all what theBigclass has to release is an array ofunsigned chars.Moreover, you won't store your
Smallinto the dynamic storage directly, for actually you are using a data member of yourBigto create it in.That being said, I'd suggest you to allocate it on the dynamic storage unless you have a good reason to do otherwise. Use a
std::unique_ptrand reset it at the beginning of the destructor ofBig. YourSmallwill go away before the body of the destructor is actually executed as expected and also in this case the destructor won't be called twice.EDIT
As suggested in the comments,
std::optionalcan be another viable solution instead ofstd::unique_ptr. Keep in mind thatstd::optionalis part of the C++17, so if you can use it mostly depends on what's the revision of the standard to which you must adhere.