C++中的单例类

Roh*_*ews 3 c++ singleton static member

我按照例子使用了singleton calss:

单身课程

但我得到的错误是"未解析的外部符号"

这是我试过的代码:

#include<iostream>
using namespace std;

class singleton
{
    int value;
    static singleton *instance;
protected:
    singleton()
    {
        value=0;
    }
public:
    static void initialize()
    {
        if(instance==NULL)
            singleton();
        else
            cout<<"An instance of singleton already exist...";
    }
    static singleton& getInstance()
    { 
        return *instance; 
    }
    int getValue() 
    { 
        return value; 
    }

};

void main()
{
    singleton::initialize();
}
Run Code Online (Sandbox Code Playgroud)

关于Singleton类的一点解释真的很棒.它使用的场景.优点和缺点.Singleton的替代品.等等

pax*_*blo 9

首先,我想:

singleton();
Run Code Online (Sandbox Code Playgroud)

应该:

instance = new singleton();
Run Code Online (Sandbox Code Playgroud)

你有它的方式,你不实际存储的新实例化对象,以便instance永远是空的.

使用以下方法显式设置静态也是一种很好的形式:

singleton *singleton::instance = 0;
Run Code Online (Sandbox Code Playgroud)

(课外定义之外).

实际上,最好从基线单例代码开始,然后从那里开始工作.这是标准格式的指针版本:

#include <iostream>

class singleton {
    protected:
        static singleton *instance;
        singleton() { }
    public:
        static singleton *getInstance() {
            if (instance == 0)
                instance = new singleton();
            return instance;
        }
};
singleton *singleton::instance = 0;

int main() {
    singleton *s1 = singleton::getInstance();
    singleton *s2 = singleton::getInstance();
    std::cout << s1 << '\n';
    std::cout << s2 << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您可以看到输出中的两个指针都是相同的:

0xbc0358
0xbc0358
Run Code Online (Sandbox Code Playgroud)

或参考版本,因为这似乎是你的目标:

#include <iostream>

class singleton {
    protected:
        static singleton *instance;
        singleton() { }
    public:
        static singleton& getInstance() {
            if (instance == 0)
                instance = new singleton();
            return *instance;
        }
};
singleton *singleton::instance = 0;

int main() {
    singleton &s1 = singleton::getInstance();
    singleton &s2 = singleton::getInstance();
    std::cout << &s1 << '\n';
    std::cout << &s2 << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Luc*_*ore 5

在定义文件中,您需要定义instance:

singleton* singleton::instance = NULL;
Run Code Online (Sandbox Code Playgroud)

如果要在多个翻译单元中使用单例,则应将定义与声明分开.

此外,它通常的方式是没有初始化方法:

static singleton* getInstance()
{ 
    if(instance==NULL)
        instance = new singleton();
    return instance;
}
Run Code Online (Sandbox Code Playgroud)

关于单身人士的好坏,有很多讨论,普遍的共识是应该避免这些单身人士.你也应该看看它们.

  • 这可能是SO的普遍共识(虽然我不确定 - 我认为这只是对手更有声音的情况),但它肯定不是一般的.单例模式被广泛使用,并且在适当的地方没有任何问题. (2认同)
  • @GMan但是这只是你说的.没有真正的证据,并且有大量有能力的程序员会为你做单身,没有问题.总的来说,除了一致认为单身人士代表一种糟糕的设计之外别无他法.事实上,非常接近于在某些情况下它们适合的共识.(现在,如果你的论点仅仅是它们可能被滥用,或者它们经常在不合适时被使用,那么许多其他C++技术也可以说同样的事情.从模板开始.) (2认同)