gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:15 27 4
gpt4 key购买 nike

我有一个“经理”类,它必须在成员被销毁后做一些清理工作:

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++ - 如何在*成员被销毁后*在析构函数中执行一些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50494286/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com