阅读有效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建筑商的尸体上没有被叫到T()的建筑? 是否是因为锅炉没有T类的数据成员,它没有T类(母子没有被暗指)的继承权?
Also, I coded this without googling for the solution, did I make any design errors?