The Singleton class cannot find ctor, but compiles, starts, and leaves an uninitialized instance.

I am having problems with my singleton pattern implementation in MSVC ++ 17 version 15.5.5. I am compiling a flag /std:c++17.

My implementation consists of the following helper class:

#pragma once
#include <cassert>

template<class T>
class Singleton : private T
{
public:
    virtual ~Singleton() = default;

    template<typename ... Targs>
    static T & initInstance(Targs && ... args)
    {
        assert(instance == nullptr);
        instance = new Singleton<T>(std::forward<Targs>(args)...); //The constructor of T might be inaccessible here so let our own ctor call it
        return *instance;
    }

    static T & getInstance()
    {
        assert(instance != nullptr);
        return *instance;
    }

private:
    template<typename ... Targs>
    explicit Singleton(Targs && ... args)
        : T{ std::forward<Targs>(args)... }
    {}

    static T * instance;
};

template<class T>
T * Singleton<T>::instance = nullptr;

, , if, , getInstance(). , , if . initInstance(), , getInstance(). , assert() , .

:

#include "Singleton.h"
#include <iostream>
class Foo
{
public:
    virtual ~Foo() = default;

protected: //has no public ctor's
    Foo(int i) //has no default ctor
        : i{ i }
    {
        std::cout << "foo ctr " << i << "\n"; //Not printed if no ctor of Foo is found
    }

private:
    int i;
};

int main(int argc, char** argv)
{
    Singleton<Foo>::initInstance(5); //Selects and executes Foo(int i).
    //Singleton<Foo>::initInstance(); //Should not compile, yet it does. Calls no ctor of Foo at all.
    Foo & theOnlyFoo = Singleton<Foo>::getInstance(); //or just use the return value of initInstance(5) to initialize this reference

    //...
    return 0;
}

:

Singleton<Foo>::initInstance(); - , Foo , . , Singleton<Foo> , Foo , . - .

, Singleton<Foo>, Foo . , instance datamember i, , , Foo .

, Foo . , Foo .

+4
1

, , , . .

, , . , () using T::T; Singleton<T>::InitInstance(), T.

0

Source: https://habr.com/ru/post/1694355/


All Articles