【发布时间】:2022-09-27 10:17:13
【问题描述】:
我希望,当我们将静态成员定义为单例实例时,getInstance() 应该始终返回相同的对象地址,所以我尝试了:
struct singleton {
static auto& getInstance() {
static auto instance = std::make_unique<singleton>();
return *instance;
}
};
int main() {
auto inst1 = singleton::getInstance();
auto inst2 = singleton::getInstance();
cout << &inst1 << endl;
cout << &inst2 << endl;
return 0;
}
它打印:
0x7ffcd729efd8
0x7ffcd729efd0
inst1 和 inst2 的地址不同,这意味着我每次调用getInstance() 时都会创建一个新对象,所以它不是一个真正的单例?
为什么地址不同?我认为 inst1 和 inst2 指向同一个对象!你能帮忙解释一下吗?
-
getInstance()每次都会返回相同的对象。但是您在inst1和inst2中创建了不同的副本。auto& inst1将创建一个引用。 -
该类仍然具有隐式生成的复制构造函数,可用于复制您在创建
inst2时所做的对象。 -
您需要使
singleton不可复制。 -
btw
instance不是该类的静态成员。
标签: c++ static singleton instance memory-address