C++/CLI中的Singleton示例?

but*_*cup 12 singleton c++-cli

我环顾四周,我需要一个适用于2个或更多C++/CLI文件的Singleton类的示例.

如何在C++/CLI中声明单例,而不是C#?

如何在两个或多个C++/CLI文件中共享该单例?

当我尝试共享该单例时,我不断获得可变重定义.

Ben*_*igt 17

这适用于C++/CLI,而不是".NET Managed Extensions for C++",即C++ .NET.不要使用Managed Extensions(Visual Studio 2002-2003),它们是错误的.

ref class Singleton
{
private:
  Singleton() {}
  Singleton(const Singleton%) { throw gcnew System::InvalidOperationException("singleton cannot be copy-constructed"); }
  static Singleton m_instance;

 public:
  static property Singleton^ Instance { Singleton^ get() { return %m_instance; } }
};
Run Code Online (Sandbox Code Playgroud)

对于"跨多个文件",同一项目中的其他编译单元使用#include,其他程序集使用引用(或#import).然后就不会有任何重新定义问题.