又一个shared_ptr的技巧

class base {};

class sub : public base {};

boost::shared_ptr<base> bb(new sub());

base的析构函数并不是virtual的,但是,离开作用域后,将调用sub的析构函数而不是base的析构函数。

shared_ptr中的两个数据成员:

T * px;                     // contained pointer
boost::detail::shared_count pn;    // reference counter


上面的代码我们调用的是下面这个构造函数:

template<class Y>
explicit shared_ptr( Y * p ): px( p ), pn( p ) // Y must be complete
{
    boost::detail::sp_enable_shared_from_this( this, p, p );
}

关键在于shared_count pn对象,它保存了对象的实际类型。

template<class Y> explicit shared_count( Y * p ): pi_( 0 )

{

    // 省略…

}

在此之前,我一直没搞懂shared_ptr的构造函数中的Y类型究竟是为了什么目的而设计出来的,今天终于知道原因了。

posted @ 2013-01-12 18:04  avexer  阅读(178)  评论(0编辑  收藏  举报