我有一个“经理”类(class),必须在 成员被销毁后对 进行某些清理:

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 的第一个创建成员,但这看起来很丑陋并且使事情依赖于顺序......

最佳答案

依赖销毁顺序确实不容易出错,假设您还发表了一条评论,说明成员顺序对特定成员很重要。出于某种原因将其放入语言中,因此使用它完全没问题。

也就是说,如果您对依赖它感到不舒服,请使用 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;
};

关于c++ - 如何在析构函数中执行一些代码 *after* 成员被销毁,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50494286/

10-17 02:01