如何在*成员被销毁后在析构函数*中执行一些代码

时间:2018-05-23 17:32:40

标签: c++ c++11 c++14

我有一位"经理"在成员被销毁之后必须进行某些清理的类:

class Manager
{
    Member a, b;

    ~Manager()
    {
        // this code will be executed BEFORE the a and b destructors
        important_cleanup();
    }
};

此处的问题是important_cleanup()使我的变量ab无效,因此他们的析构函数失败。

这个问题还有很好的解决方法吗?

PS 我知道我可以定义某种clenup成员,并使其成为Manager的第一个创建成员,但这看起来非常丑陋,并且使得依赖于顺序。

1 个答案:

答案 0 :(得分:4)

依赖销毁订单确实不容易出错,假设您还发表评论,指出成员订单对特定成员很重要。由于某种原因,它被放入语言中,因此使用它完全没问题。

那就是说,如果你依赖它感到不舒服,destructors of members are called before those of the base classes,所以你可以使用基类来做到这一点:

class ManagerCleanup {
public:
    ~ManagerCleanup() {
        important_cleanup();
    }

private:
    some_native_resource resource;
};

// Might as well inherit privately
class Manager : private ManagerCleanup
{
    Member a, b;
};

请注意,如果您包装资源,它会更加惯用:

// Note: this could probably be a std::unique_ptr. std::unique_ptr can
// manage arbitrary resources, not just pointers.
class ItemRequiringCleanup {
public:
    // Ensure you implement/disable copy/move operations appropriately

    ~ItemRequiringCleanup() {
        important_cleanup();
    }

private:
    some_native_resource resource;
};

class ManagerCleanup {
private: // or protected:
    ItemRequiringCleanup resource;
};

// Might as well inherit privately
class Manager : private ManagerCleanup
{
    Member a, b;
};