Question

I'm reading Effective C++, so I tried to implement the class that prevents construction of multiple objects (Item 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;
}

How come the T() construction of the boolWrapper is not called before the body of the boolWrapper constructor? Is it because boolWrapper has no data member of type T, and it doesn't inherit from T (no parent ctor gets called implicitly)?

Also, I coded this without googling for the solution, did I make any design errors?

Was it helpful?

Solution

The problem in the code you posted is that boolWrapper has no data member of type T. Inside a class constructor, constructors (default ones) are called for base classes and for data members (if not explicit constructors are mentioned in the initialization list).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top