0
#include <stdio.h>

template <typename T>
class Singleton
{
public:
    static T &GetInstance()
    {
        static T instance;
        return instance;
    }

protected:
    Singleton() = default;

private:
    // Delete copy/move so extra instances can't be created/moved.
    Singleton(const Singleton &) = delete;
    Singleton &operator=(const Singleton &) = delete;
    Singleton(Singleton &&) = delete;
    Singleton &operator=(Singleton &&) = delete;
};

class TestSingleton : public Singleton<TestSingleton>
{
public:
    void print() { printf("%p TestSingleton\n", this); }
private:
    TestSingleton() = default;
    friend class Singleton<TestSingleton>;
};

inline TestSingleton &GetTestSingleton()
{
    printf("func TestSingleton\n");
    return TestSingleton::GetInstance();
}

int main()
{
    // should not work.
    TestSingleton().print();

    GetTestSingleton().print();
    GetTestSingleton().print();
    GetTestSingleton().print();

    // not work as expected
    // TestSingleton test_copy = GetTestSingleton();

    return 0;
}

how to forbiden TestSingleton instance out of Singleton, except writeprivate: TestSingleton() = default; friend class Singleton<TestSingleton>;. anyone has good idea? related articles following:https://en.wikipedia.org/wiki/Singleton_pattern

C++ Singleton design pattern

justin
  • 1
  • 1
  • I do not see any CRTP, anyway the first question you need to ask yourself is why you would need a singleton in the first place. I often make an abstract base class (interface) with getters/operations I need. Then create an instance of a derived concrete class in main and pass the interface around to objects that need the "global" information. This pattern is called dependency injection an is much better testable/maintainable in the long run (https://en.wikipedia.org/wiki/Dependency_inversion_principle). Read this too: https://www.fluentcpp.com/2018/03/06/issues-singletons-signals/ – Pepijn Kramer Jul 22 '22 at 08:24
  • CRTP: `class TestSingleton : public Singleton` ? – justin Jul 22 '22 at 08:34
  • Sorry Justin, me bad ... missed that bit ;) – Pepijn Kramer Jul 22 '22 at 08:36
  • sorry for what? – justin Jul 29 '22 at 07:55
  • For missing the CRTP bit in your code :) – Pepijn Kramer Jul 29 '22 at 12:48

0 Answers0