测试" Singleton with new and delete(C ++)"

时间:2016-07-21 11:35:44

标签: c++ singleton new-operator delete-operator

我已经阅读了这篇关于C ++新增和删除的link。有一个代码实现了Singleton模式。我测试了这段代码:

#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 

为什么不打印&#34;字符串s&#34;?如果我更改注释行,则t可以打印出&#34; string s&#34;。

1 个答案:

答案 0 :(得分:2)

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

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

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