shared_ptr 创建时即捕获析构动作,何解?

读陈硕书《Linux多线程服务端编程》,有一句话不能理解:析构在创建时被捕获,这意味着虚析构不再是必须的。实际代码操作了一下,发现确实通过shared_ptr去释放派生类对象,无需将析构函数置为virtual,代码如下:

#include <iostream>

template <typename Base>
class simple_ptr_internal_interface {
public:
    virtual Base* get() = 0;
    virtual void destruct() = 0;
}; // class simple_ptr_internal_interface

template <typename Base, typename Derived>
class simple_ptr_internal: public simple_ptr_internal_interface<Base>
{
public:
    struct DefaultDeleter {
        void operator()(Base* t) { delete static_cast<Derived*>(t); }
    };
    simple_ptr_internal(Base* p): pointer(p) {}

    virtual Base* get() override { return pointer; }
    virtual void destruct() override { deleter(pointer); }

private:
    Base* pointer;
    DefaultDeleter deleter;
}; // class simple_ptr_internal

template <typename Base>
class simple_ptr {
public:
    template <typename Derived>
    simple_ptr(Derived* d): internal(new simple_ptr_internal<Base, Derived>{d}) {}
    ~simple_ptr() { this->destruct(); }

private:
    void destruct() { internal->destruct(); }
    simple_ptr_internal_interface<Base>* internal;
}; 

class base
{
public:
    base(){std::cout << "base construct" << std::endl;}
    ~base(){std::cout << "base destruct" << std::endl;}
};

class derived: public base
{
public:
    derived(){std::cout << "derived construct " << std::endl;}
    ~derived(){std::cout << "derived destruct" << std::endl;}
};

int main()
{
    simple_ptr<base>(new derived());
    return 0;
}

代码打印为:

base construct
derived construct 
derived destruct
base destruct
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值