为什么shared_ptr <base />正确地破坏Derived对象,即使未实现虚拟析构函数

时间:2017-04-06 06:34:33

标签: c++ c++11 shared-ptr unique-ptr

在我的代码中,我遇到了一个基类没有虚拟析构函数的错误,如果通过基类指针销毁派生类对象,肯定会导致内存泄漏。

对此感到好奇,我写了以下程序:

#include <iostream>
#include <memory>
#include <vector>


class Interface {
    public:
        virtual void f() = 0;
};


class Printer {
    public:
        ~Printer() {
            std::cout << "Printer Dtor is called " << std::endl;
        }
};


class Client : public Interface {
    public:
        std::vector<Printer> member;
        Client() : member(4) {}
        virtual void f() override final {};

};


int main() {
    {
        std::cout << "Unique pointer is created" << std::endl;
        std::unique_ptr<Interface> ptr = std::make_unique<Client>();
        std::cout << "Unique pointer goes out of the scope" << std::endl;
    }

    {
        std::cout << "Shared pointer is created" << std::endl;
        std::shared_ptr<Interface> ptr = std::make_shared<Client>();
        std::cout << "Shared pointer goes out of the scope" << std::endl;
    }

    {
        std::cout << "Shared pointer is created" << std::endl;
        std::shared_ptr<Interface> ptr = std::shared_ptr<Client>(new Client);
        std::cout << "Shared pointer goes out of the scope" << std::endl;
    }

    return 0;
}

结果非常惊讶:

Unique pointer is created
Unique pointer goes out of the scope
Shared pointer is created
Shared pointer goes out of the scope
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called
Shared pointer is created
Shared pointer goes out of the scope
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called

如果shared_ptr vector被调用,unique_ptr的析构函数被调用,shared_ptr我们有内存泄漏。

spring cloud config server如何知道要调用哪个析构函数?

0 个答案:

没有答案