C++ Singleton - Prevent ::instance() to variable

C++ Singleton - Prevent ::instance() to variable

本文关键字:to variable instance Prevent C++ Singleton      更新时间:2023-10-16

给定singleton类

class MySingleton
{
// ...
public:
MySingleTon& instance() { /* ... */ }
};

有可能防止吗:

int main()
{
// the following should cause some error
MySingleton& singleton = MySingleton::instance();
}

同时仍然允许:

int main()
{
// Only directly accessing MySingleton::instance().SomeMethod should be possible
MySingleton::instance().some_method();
}

额外示例

int main()
{
// Following two lines should error
MySingleton& singleton = MySingleton::instance();
singleton.some_method();

// Following line should NOT error
// Additionally it should be the only way to access any MySingleton method besides MySingleton::instance
MySingleton::instance().some_method();
}

我知道的唯一方法是使instance()本身成为private,这样MySingleton之外的代码就不能直接调用它,然后向MySingleton添加一个static方法,即public,并根据需要在内部使用instance(),例如:

class MySingleton
{
// ...
private:
MySingleton() { /* ... */ }
static MySingleton& instance() {  static MySingleton inst; return inst; }
public:
static void do_method() { instance().some_method(); }
};
int main()
{
MySingleton& singleton = MySingleton::instance(); // <-- ERROR
singleton.some_method();

MySingleton::do_method(); // <-- OK
}