C++ Singleton - Prevent ::instance() to variable
C++ Singleton - Prevent ::instance() to variable
给定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
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- Python str to C++ to Python str
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- System.InvalidCastException - SQL to C++ - safe_cast<float>
- Cppcheck "Reference to auto variable returned"失败的原因?
- 是否有用于"go to variable type definition" C++中"auto"变量的 Visual Studio 键盘快捷方式?
- C++ dll variable to vb.net exe
- stdout to a variable c/c++
- DsGetDomainControllerInfo 返回一个"Pointer to a pointer variable that receives an array" ?我不明白
- C++ " reference to local variable returned "
- 'variable' 不是类型 'pointer to member function' 的有效模板参数
- Eclipse "assign to new local variable" (crtl+2-l) 不适用于 c++?