在Jon的网站上,他在C#中使用了这个优雅设计的单例,如下所示:
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何在C++中编写等效代码?我有这个,但我不确定它是否实际上具有与Jon相同的功能.(顺便说一下,这只是一个星期五的练习,不需要任何特别的东西).
class Nested;
class Singleton
{
public:
Singleton() {;}
static Singleton& Instance() { return Nested::instance(); }
class Nested
{
public:
Nested() {;}
static Singleton& instance() { static Singleton inst; return inst; }
};
};
...
Singleton S = Singleton::Instance();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3224 次 |
| 最近记录: |