gpt4 book ai didi

c++ - 为什么 std::shared_ptr 从基类和派生类调用析构函数,而 delete 只调用基类的析构函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:47:39 25 4
gpt4 key购买 nike

<分区>

为什么在使用 std::shared_ptr 释放时从基类和派生类调用析构函数,而第二个示例仅从基类调用析构函数?

class Base
{
public:
~Base()
{
std::cout << "Base destructor" << std::endl;
}
};

class Derived : public Base
{
public:
~Derived()
{
std::cout << "Derived destructor" << std::endl;
}
};

void virtual_destructor()
{
{
std::cout << "--------------------" << std::endl;
std::shared_ptr<Base> sharedA(new Derived);
}

std::cout << "--------------------" << std::endl;
Base * a = new Derived;
delete a;
}

输出:

--------------------
Derived destructor
Base destructor
--------------------
Base destructor

我原以为这两种情况下会有相同的行为。

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