-2

I can see everybody recommending to add delete to all copy constructor / move / assignment operator, but doing all this I can still assign the instance. Here is my singleton code :

class SingleTone
{
public:

    SingleTone(SingleTone& other) = delete;
    SingleTone& operator=(const SingleTone&) = delete;
    SingleTone& operator=(SingleTone&&) = delete;
    SingleTone* operator=(const SingleTone*) = delete;

     
    static SingleTone* instance()
    {
        if (singletone == nullptr)
        {
            singletone = new SingleTone();
        }
        return singletone;
    }
    int get1()
    {
        return 1;
    }
private:
    SingleTone() {};
    static SingleTone* singletone;
};

SingleTone* SingleTone::singletone = nullptr;

But in main, I can still do:

SingleTone *ss = SingleTone::instance();

Now I will have 2 instances.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
user63898
  • 29,839
  • 85
  • 272
  • 514
  • instance return a pointer, you are deleting operation over the object, not its pointer. Check the pointer value it will be the same – Alessandro Teruzzi Feb 11 '23 at 17:35
  • 1
    See also [Is Meyers' implementation of the Singleton pattern thread safe?](https://stackoverflow.com/questions/1661529/is-meyers-implementation-of-the-singleton-pattern-thread-safe) which is less code and also thread-safe. – Richard Critten Feb 11 '23 at 17:40
  • 1
    Change to `static SingleTone& instance()` to return by reference of the one instance. – Eljay Feb 11 '23 at 17:55
  • 1
    You are copying a pointer, and no amount of deleting of constructors will stop that happening, since no objects are constructed when you copy a pointer. Clearly you have two pointers pointing at the same single instance. – john Feb 11 '23 at 17:56
  • *"`SingleTone* operator=(const SingleTone*)`"* -- this is not one of the standard assignment operators, so there is no need to introduce it only to declare (via `=delete`) that it does not exist. (Also, this operator would not handle the case that I suspect you think it does.) – JaMiT Feb 11 '23 at 18:36

1 Answers1

1

No you will have multiple pointers to the same instance. As @Richard Critten mentioned Meyers' implementation of the Singleton along with other benefits will not allow multiple pointers.

    static SingleTone& instance()
    {
        static SingleTone singletone; //remove singletone private member
        return singletone;
    }
user10
  • 266
  • 5