防止构建多个对象

时间:2012-05-11 09:45:07

标签: c++ singleton effective-c++

我正在阅读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被隐式调用)?

另外,我编写了这个没有谷歌搜索解决方案,我做了任何设计错误?

1 个答案:

答案 0 :(得分:1)

您发布的代码中的问题是boolWrapper没有类型T的数据成员。在类构造函数中,构造函数(默认值)被调用用于基类和数据成员(如果初始化中没有提到显式构造函数)列表)。