我在使用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)
}
完。