C++ 单例 - 防止 ::instance() 成为变量
C++ Singleton - Prevent ::instance() to variable
给定单例class
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
}
给定单例class
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
}