c++ - boost::~shared_ptr 是如何工作的?

标签 c++ boost shared-ptr

在阅读《Beyond the C++ Standard Library: An Introduction to Boost》时,我得到了一个非常有趣的例子:

class A  
{  
public:  
    virtual void sing()=0;  
protected:  
    virtual ~A() {};  
};

class B : public A
{  
public:  
    virtual void sing(  )  
    {  
       std::cout << "Do re mi fa so la"<<std::endl;;  
    }  
};  

我做了一些测试:

int main()
{  

//1  
std::auto_ptr<A> a(new B); //will not compile ,error: ‘virtual A::~A()’ is protected

//2
A *pa = new B;
delete pa;  //will not compile ,error: ‘virtual A::~A()’ is protected
delete (dynamic_cast<B*>(pa)); //ok

//3 
boost::shared_ptr<A> a(new B);//ok

}

我很好奇的是 ~shared_ptr 是如何工作的? 它是如何推导出派生类B的?

提前感谢您的帮助!

谢谢大家, 我写了一个关于 ~shared_ptr 如何工作的简单示例

class sp_counted_base
{
public:
    virtual ~sp_counted_base(){}
};

template<typename T>
class sp_counted_base_impl : public sp_counted_base
{
public:
    sp_counted_base_impl(T *t):t_(t){}
    ~sp_counted_base_impl(){delete t_;}
private:
    T *t_;
};


class shared_count
{
public:
    static int count_;
    template<typename T>
    shared_count(T *t):
        t_(new sp_counted_base_impl<T>(t))
    {
        count_ ++;
    }
    void release()
    {
        --count_;
        if(0 == count_) delete t_;
    }
    ~shared_count()
    {
        release();
    }
private:
    sp_counted_base *t_;
};
int shared_count::count_(0);

template<typename T>
class myautoptr
{
public:
    template<typename Y>
    myautoptr(Y* y):sc_(y),t_(y){}
    ~myautoptr(){ sc_.release();}
private:
    shared_count sc_;
    T *t_;
};

int main()
{
    myautoptr<A> a(new B);
}

关键是:

  1. 模板构造函数
  2. ~shared_ptr中没有被删除的资源,被shared_count删除了

最佳答案

令人惊讶的是,这里的关键不是boost::shared_ptr析构函数,但它的构造函数。

如果您查看 boost/shared_ptr.hpp , 你会看到 shared_ptr<T>没有“简单”的构造函数期望 T *但是:

template<class Y>
explicit shared_ptr( Y * p );

//3当你构建一个 boost::shared_ptr来自 B * , 未转换为 A *发生,shared_ptr内部是用实际的 B 构建的类型。销毁对象后,删除发生在 B指针(不是通过基类指针)。

关于c++ - boost::~shared_ptr 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4560372/

相关文章:

c++11 - 为特定类型的 shared_ptr 创建默认删除器

c++ - 快速找到不开心号码的方法

c++ - Boost.Graph:使用名称保存和加载 boost::adjacency_list

c++ - Boost 线程中断在跨越 DLL 边界时不起作用

c++ - 将 local_date_time CET boost 为 UTC

c++ - 具有成员函数和携带参数的构造函数的多线程

c++ - 超出范围后在 Lambda 中设置共享指针

c++ - Win32 位图渲染速度如何比像素快?

c++ - 在 C# 中加载非托管 C++。错误尝试读取或写入 protected 内存

c++ - 使用 C++ 在上下文菜单 shell 扩展中级联子菜单