测试时的问题 "Singleton with new and delete (C++)"

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

我读过这个 link 关于 C++ 中的 new 和 delete 的内容。有一个实现单例模式的代码。我已经测试了这段代码:

#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;
}

但结果是:

operator new
operator new nullptr
s string s
operator new
t 

为什么没有打印出来"string s"?如果我更改注释行,则可以打印出 "string s".

语句new Singleton会调用operator new获取存储空间,然后使用默认构造函数初始化对象的非静态成员。

由于 _s 不是静态的,每次创建新的 Singleton 时都会(重新)初始化它。因此将导致 t.

的空白字符串

UB 很有可能以这种方式为 _s 成员重用 space。