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

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

#include 
#include 
using namespace std;

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

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

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

代码打印为:

base construct
derived construct 
derived destruct
base destruct



而后阅读文章[c++ 笔记]shared_ptr 理解创建时即捕获析构动作,感觉该文章给出了一个较为合理的解释,不过模拟shared_ptr原理的代码编译不过,这边稍作修改

#include 

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

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

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

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

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

private:
    void destruct() { internal->destruct(); }
    simple_ptr_internal_interface<T>* 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

你可能感兴趣的:(Linux多线程服务端编程,c++,c++,智能指针,shared_ptr)