有没有办法在类析构函数之前调用字段析构函数?
假设我有 2 个类Small和Big, 并Big包含一个实例Small作为其字段:
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;
}
当然,这会在小析构函数之前调用大析构函数:
Big destructor
Small destructor
我需要在Small析构函数之前调用Big析构函数,因为它为Big析构函数做了一些必要的清理。
我可以:
- 显式调用
small.~Small()析构函数。-> 然而,这会调用Small析构函数两次:一次是显式调用,一次是在Big析构函数执行后调用。 - 将a
Small*作为字段并调用析构函数delete small;Big
我知道我可以在Small类中有一个函数来进行清理并在Big析构函数中调用它,但我想知道是否有办法反转析构函数的顺序。
有没有更好的方法来做到这一点?