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

时间:2020-02-04 00:42:59

标签: c++ class oop design-patterns

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

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

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

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

1 个答案:

答案 0 :(得分:0)

您可以在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;
}