我已经阅读了这篇关于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;。
答案 0 :(得分:2)
语句new Singleton
将调用operator new
获取存储,然后使用默认构造函数初始化对象的非静态成员。
由于_s
不是静态的,因此每次创建新Singleton
时都会(重新)初始化它。因此会导致t
的空白字符串。
UB很可能以这种方式为_s
成员重用空间。