gpt4 book ai didi

c++ - 你能防止在没有实例化的情况下调用构造函数吗?

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

我类(class)的简化片段:

class UpdatingSystem
/* when system is "unsafe" it marks this condition by instantiating an
UpdatingSystem item. While this item exists errors are handled in a
particular way. When the UpdatingSystem item goes out of scope error
handling reverts to normal.*/
{
private:
static THREAD int updatingSystemCount_;

public:
UpdatingSystem(const char* caller){updatingSystemCount++};
~UpdatingSystem(){updatingSystemCount--};
};

这个有效:

{
UpdatingSystem tempUnsafe("Reason it's unsafe");
// do stuff that requires the system be 'unsafe'
} // Revert to safe when destructor runs

这不是:

{
UpdatingSystem("Reason it's unsafe");
// do stuff that requires the system be 'unsafe'
}

...因为被调用的构造函数创建了一个临时项,而析构函数立即运行,使系统在不应该的时候保持“安全”状态。

编写错误的第二个版本很容易出错。有没有办法防止在没有实例化的情况下调用构造函数?

最佳答案

Is there a way to prevent such a call of the constructor without instantiation?

不,您无法控制用户如何实例化您的类。

也许更好的名称会鼓励正确使用,例如:

class SystemUpdateGuard {..}

{
SystemUpdateGuard guard_system_update("Reason it's unsafe");
// do stuff that requires the system be 'unsafe'
} // Revert to safe when destructor runs

关于c++ - 你能防止在没有实例化的情况下调用构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41285452/

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