如何保证一个类只有一个实例(1)

方法:

给类写一个静态函数

static myClass* instance()
{
        static myClass ins;
        return &ins;
};

采用如下方式得到一个myClass的实例:

myClass::instance();

问题:

众所周知,函数体内局部变量的生命周期是函数的存在期。在instance()消亡以后,内存中仍然存在一个static的myCalss实例ins。这在逻辑上存在矛盾。

正因为这种矛盾,C#中废止了这种函数体内的static变量。

原文地址:https://www.cnblogs.com/mumuliang/p/1873574.html