gpt4 book ai didi

c++ - 如何设计类方法只能被调用一次

转载 作者:行者123 更新时间:2023-12-02 10:36:30 25 4
gpt4 key购买 nike

我有状态类,一旦创建了一个类实例,它的Bar函数/方法只能被调用一次,否则内部状态会混乱。如何设计这样的东西?

可以在编译时发出警告/错误的东西会更好。

class  Foo {
bool Bar(string arg...) { do something...}

// some class member
string s;
int i;
}

最佳答案

您可以在Foo::Bar()中定义一个静态标志,以跟踪该函数是否已被调用:

bool Foo::Bar() {
static bool has_been_called; // initialized to false

if (!has_been_called) {
has_been_called = true
// ...
// do something
// ...
return true;
}

return false;
}

对于多个线程可以调用成员函数的情况,您可以
改用 std::call_once() ;因为上面标志 has_been_called的读取与写入不同步。
bool Bar() {
static std::once_flag flag;

bool executed = false;

std::call_once(flag, [this, &executed]() {
// ...
// do something
// ...
executed = true;
});
return executed;
}

关于c++ - 如何设计类方法只能被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60049060/

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