C++ destruction order: Calling a field destructor before the class destructor

Viewed 1738

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:

  1. call the small.~Small() destructor explicitly. -> This, however, calls the Small destructor twice: once explicitly, and once after the Big destructor has been executed.
  2. have a Small* as the field and call delete small; in the Big destructor

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?

3 Answers
Related