我正在阅读 Effective C++,所以我尝试实现防止构造多个对象的类(第 4 项):
#include <iostream>
using namespace std;
class testType
{
public:
testType()
{
std::cout << "TestType Ctor called." << std::endl;
}
};
template <typename T, class C>
class boolWrapper
{
public:
boolWrapper()
// Shouldn't T() be called here in the initialization list, before the
// body of the boolWrapper?
{
if (C::exists)
{
std::cout << "Oh, it exists." << endl;
}
else
{
std::cout << "Hey, it doesn't exist." << endl;
C::exists = true;
T();
}
}
};
template<class T>
class singleton
{
private:
static bool exists;
boolWrapper<T, singleton> data_;
public:
singleton()
:
data_()
{
};
friend class boolWrapper<T, singleton>;
};
template <class T>
bool singleton<T>::exists = false;
int main(int argc, const char *argv[])
{
singleton<testType> s;
singleton<testType> q;
singleton<testType> r;
return 0;
}
为什么在 boolWrapper 构造函数的主体之前没有调用 boolWrapper 的 T() 构造?是不是因为 boolWrapper 没有 T 类型的数据成员,并且它没有从 T 继承(没有隐式调用父 ctor)?
另外,我在没有搜索解决方案的情况下进行了编码,我是否犯了任何设计错误?