c++ - 单例示例如何工作

标签 c++ singleton

我在 C++ 语言中找到了这个单例示例:

#include <iostream>

class singleton {
private:
    // ecco il costruttore privato in modo che l'utente non possa istanziare direttamante
    singleton() { };
public:
    static singleton& get_instance() 
    {
            // l'unica istanza della classe viene creata alla prima chiamata di get_instance()
            // e verrà distrutta solo all'uscita dal programma
        static singleton instance;
        return instance;
    }
    bool method() { return true; };
};

int main() {
    std::cout << singleton::get_instance().method() << std::endl;

    return 0;
}

但是,这怎么可能是单例类呢?

只创建一个实例的控件在哪里?

不要错过静态属性?

如果我在主函数中编写另一个 get_instance() 调用会怎样?

最佳答案

单实例控制是使用 get_instance 中的函数范围静态完成的。此类对象在程序流首先通过它们时构造一次,并在程序退出时销毁。因此,您第一次调用 get_instance 时,将构造并返回单例。每隔一段时间将返回相同的对象

这通常称为 Meyers singleton .

关于c++ - 单例示例如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34787288/

相关文章:

c++ - STL 映射 - 插入或更新

c++ - 计算区间内数字频率的类

c++ - "Run-Time Check Failure #0 - The value of ESP"调用dll函数时

javascript - Javascript 中的单例模式与全局变量用例?

android - 通过服务和 Activity 共享单例java类

c++ - 在 Qt 4.8 中集成 OGRE 1.7.3

c++ - 如何在 Visual Studio 2005 (C++) 中声明复杂变量

android - 在 android 中使用 Singleton 模式是一种不好的做法吗?

swift - 关于 Swift 中的单例模式

java - 在多线程环境中是否可以仅通过一个线程使用单例实例?