包含模板的单身人士

时间:2017-03-02 12:38:46

标签: c++ templates singleton

#include<iostream>
#include<mutex>
#include<stdlib.h>
using namespace std;

template<typename T>
class Singleton {
public:
    static T& getInstance() {
        if (instance_ == nullptr){
            std::lock_guard<mutex> guard(mutex_);
            if (instance_ == nullptr) {
                instance_ = new T();
                atexit(&Singleton::destroy);
            }
        }
        return *instance_;
    }
private:
    static void destroy() {
        delete instance_;
        instance_ = nullptr;
    }
    Singleton() {}
    Singleton(const Singleton&) {}
    Singleton& operator=(const Singleton&) {}
    static T* instance_;
    static mutex mutex_;
};
template<typename T>
T* Singleton<T>::instance_ = nullptr;
template<typename T>
mutex Singleton<T>::mutex_;

class Test {
public:
    Test() { 
        i_ = 0;
        cout << "Construct Test" << endl; 
    }
    void setValue(int&& x) {
        i_ = x;
    }
    int getValue() {
        return i_;
    }
private:
    int i_;
};
void main(){
    auto instance1 = Singleton<Test>::getInstance();
    auto instance2 = Singleton<Test>::getInstance();
    instance1.setValue(2);
    cout << instance2.getValue() << endl;
    cout << instance1.getValue() << endl;
    system("pause");
}

为什么instance1和instance2的类型是Test not Test&amp; ? “构造测试”只打印一次,但结果是0和2,instancen1和instance2看起来是两个不同的Test对象,环境是vs2015

1 个答案:

答案 0 :(得分:0)

  

为什么instance1和instance2的类型是Test not Test&amp; ?

因为您需要使用auto&代替auto

auto& instance1 = Singleton<Test>::getInstance();
auto& instance2 = Singleton<Test>::getInstance();

您可以验证是否正在复制而不是使用复制构造函数获取对单例变量的引用

Test(const Test&) {
    cout << "Copying";
}

规则是

int i = 5;
auto a1 = i;    // value
auto & a2 = i;  // reference

我还会关注Baum mit Augen的评论,并避免首先使用void mainstdlib.h