【问题标题】:Singleton with template [duplicate]带有模板的单例 [重复]
【发布时间】:2017-03-02 12:38:45
【问题描述】:
#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 而不是 Test& ? “Construct Test”只打印一次,但结果是0和2,instancen1和instance2好像是两个不同的Test对象,Environment是vs2015

【问题讨论】:

  • 另外,void main 不是合法的 C++,#include&lt;stdlib.h&gt; 自第一个标准以来已被弃用。
  • 与单例无关:autowotks 作为模板推导。

标签: c++ templates singleton


【解决方案1】:

为什么instance1和instance2的类型是Test而不是Test&?

因为您需要使用auto&amp; 代替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

【讨论】:

  • 谢谢,当我使用 Singleton& instance1 = Singleton::getInstance();它不能工作,为什么?
  • @HbShi 你在为instance1instance2 做这件事吗?
  • 两者或只有一个都不能
  • @HbShi 我忽略了:Singleton&lt;Test&gt; 是错误的,您正在返回对单例管理对象的引用。你应该同时做:Test&amp; instance1 = ...; Test&amp; instance2 = ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 2013-02-11
  • 2021-03-20
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多