静态unique_ptr两次调用析构函数

cav*_*gru 2 c++ singleton lazy-loading unique-ptr c++11

我使用单例模式,该模式返回对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;
}
Run Code Online (Sandbox Code Playgroud)

我期望类的析构函数只调用一次,但是尽管构造函数调用了一次,析构函数调用了两次,但这是输出,

main starts!
Lazy::Lazy() 0xb1ec20
auto state = Settings::lazy() 0x7ffe17ae18b8
main ends!
Lazy::~Lazy() 0x7ffe17ae18b8
Lazy::~Lazy() 0xb1ec20
Run Code Online (Sandbox Code Playgroud)

为什么析构函数调用两次?甚至第二个呼叫,此地址也不同。

Rak*_*111 7

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

之所以要2个单身,是因为当您获得单身时,会auto state = Settings::lazy();创建一个副本。您可能正在返回参考,但state不是参考,因此将创建一个副本。

制作state参考解决了这个问题:auto& state = Settings::lazy();