boost::shared_ptr基础知识

我在使用boost的智能指针,但是对其用法很模糊,比如“if (ptr == nullptr)”和“if (!ptr)”是不是等价的、等,遂调用了它的常用函数,同时将源码也注释到后面了,这样看着就很舒服明朗了。

#include <boost/shared_ptr.hpp>
struct MyStruct
{
    int i;
    float f;
};
typedef boost::shared_ptr<MyStruct> MyStructPtr;
int main()
{
    MyStruct* px = 0x0;
    //
    //智能指针其实是一个类对象,它有两个成员,px存储指针的值,pn进行计数。
    MyStructPtr my1;                 // shared_ptr<T>::shared_ptr() BOOST_NOEXCEPT : px( 0 ), pn() /* never throws in 1.30+ */ { }
    MyStructPtr my3 = MyStructPtr(); // shared_ptr<T>::shared_ptr() BOOST_NOEXCEPT : px( 0 ), pn() /* never throws in 1.30+ */ { }
    MyStructPtr my2 = nullptr;       // shared_ptr<T>::shared_ptr( boost::detail::sp_nullptr_t ) BOOST_NOEXCEPT : px( 0 ), pn() { }
    MyStructPtr my4 = MyStructPtr(new MyStruct);
    //
    px = my1.get(); // element_type * get() const BOOST_NOEXCEPT { return px; }
    my1.operator bool(); // explicit operator bool () const BOOST_NOEXCEPT { return px != 0; }
    my1.operator!(); // bool operator! () const BOOST_NOEXCEPT { return px == 0; }
    my4.operator*(); // typename boost::detail::sp_dereference< T >::type operator* () const { return *px; } //返回的是一个引用,所以没有对象的拷贝。
    my4.operator->(); // typename boost::detail::sp_member_access< T >::type operator-> () const { return px; }
    my1.operator=(my2);
    //
    (nullptr == my1); // template<class T> inline bool operator==(boost::detail::sp_nullptr_t, shared_ptr<T> const & p) BOOST_NOEXCEPT { return p.get() == 0; }
    (my1 == my2); // template<class T, class U> inline bool operator==(shared_ptr<T> const & a, shared_ptr<U> const & b) BOOST_NOEXCEPT { return a.get() == b.get(); }
    //
    my1.use_count(); // 引用计数
    my1.unique(); // 是否唯一(use_count() == 1 ? true : false)
}

完。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值