【问题标题】:c++ using static member as singleton instance leads to different objectc++ 使用静态成员作为单例实例导致不同的对象
【发布时间】: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 指向同一个对象!你能帮忙解释一下吗?

标签: c++ static singleton instance memory-address


【解决方案1】:

该班有隐式合成的复制构造函数singleton::singleton(const singleton&amp;) 在创建 inst2 时使用。

//this is copy initialization
auto inst2 = singleton::getInstance(); //works because of accessible copy ctor

inst1 也是如此。

您可以使用auto&amp; 创建左值引用(别名)或使类不可复制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多