gpt4 book ai didi

c++ - static unique_ptr 两次调用析构函数

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:20 27 4
gpt4 key购买 nike

我使用单例模式返回对 unique_ptr 取消引用的引用。这是代码,

#include <iostream>
#include <memory>
using std::cout; using std::endl;
using std::unique_ptr;

namespace Settings {
class Lazy {
Lazy() { cout << "Lazy::Lazy() " << this << endl; }
public:
~Lazy() { cout << "Lazy::~Lazy() " << this << endl; }
static Lazy &instance()
{
static unique_ptr<Lazy> lazy(new Lazy);
return *lazy;
}
};

Lazy &lazy()
{ return Lazy::instance(); }
}

int main()
{
cout << "main starts!" << endl;
auto state = Settings::lazy();
cout << "auto state = Settings::lazy() " << &state << endl;

cout << "main ends!" << endl;
return 0;
}

我原以为类的析构函数只会调用一次,但尽管构造函数调用一次,析构函数调用两次,但这是输出,

main starts!
Lazy::Lazy() 0xb1ec20
auto state = Settings::lazy() 0x7ffe17ae18b8
main ends!
Lazy::~Lazy() 0x7ffe17ae18b8
Lazy::~Lazy() 0xb1ec20

为什么析构函数调用了两次?甚至第二次调用这个地址也是不同的。

最佳答案

因为您有 2 个单例实例,并且都被销毁了。

您必须使用 2 个单例的原因是,当您获得单例时 auto state = Settings::lazy(); 会创建一个拷贝。您可能会返回一个引用,但 state 不是一个引用,因此会创建一个拷贝。

使 state 成为引用可以解决问题:auto& state = Settings::lazy();

关于c++ - static unique_ptr 两次调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36241068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com