【发布时间】: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<stdlib.h>自第一个标准以来已被弃用。 -
与单例无关:
autowotks 作为模板推导。