我试图创建一个单身时想出了这个.示例:(我正在尝试创建MySelf一个单例,它是线程安全的,不使用双重检查锁定)
class MySelf
{
private:
string Name;
int Age;
MySelf()
{
Name = "Deamonpog";
Age = 24;
cout << "Constructing MySelf : " << Name << endl;
};
friend class MySingleton;
public:
~MySelf(){ cout << "Destructing MySelf : " << Name << endl; };
int MyAge() const
{
return Age;
}
};
class MySingleton
{
private:
static MySelf mself;
public:
static MySelf * GetInstance()
{
return &mself;
}
};
MySelf MySingleton::mself;
Run Code Online (Sandbox Code Playgroud)
现在我可以很容易地使用它,像
cout << "I am " << …Run Code Online (Sandbox Code Playgroud)