Search code examples
c++singletonnew-operatordelete-operator

Issue when test "Singleton with new and delete (C++)"


I have read this link about new and delete in C++. There is a code that implemented Singleton pattern. I have tested this code:

#include <iostream>
#include <memory>

class Singleton {
    static Singleton *instance;
    static std::size_t refcount;
    std::string _s;

  public:
    void setS(std::string s) { _s = s; }
    std::string getS() { return _s; }
    static void *operator new(std::size_t nbytes) throw (std::bad_alloc) {
        std::cout << "operator new" << std::endl;
        if (instance == nullptr) {
            std::cout << "operator new nullptr" << std::endl;
            instance = ::new Singleton; // Use the default allocator
        }
        refcount++;
        return instance;
    }

    static void operator delete(void *p) {
        std::cout << "operator delete" << std::endl;
        if (--refcount == 0) {
            std::cout << "operator delete" << refcount << std::endl;
            ::delete instance;
            instance = nullptr;
        }
    }
};

Singleton *Singleton::instance = nullptr;
std::size_t Singleton::refcount = 0;

int main() {
  Singleton* s = new Singleton;
  //Singleton* t = new Singleton;
  s->setS("string s");
  std::cout << "s " << s->getS() << std::endl;
  Singleton* t = new Singleton;
  std::cout << "t " << t->getS() << std::endl;
  return 0;
}

But the result is:

operator new
operator new nullptr
s string s
operator new
t 

Why t didn't print out "string s"? If I change the comment line, t can print out "string s".


Solution

  • The statement new Singleton will call operator new to aquire storage, and then intialize the non-static members of the object using the default constructor.

    As _s is not static, it will be (re)initialized every time a new Singleton is created. So will result in a blank string for t.

    It is very likely UB to reuse the space for the _s member this way.