[ shared_ptr ]

The shared_ptr is a reference-count smart pointer. It keeps information about the controlled resource so that it can be automatically freed when no longer needed.

Constructor:

#include <tr1/memory>
using std::tr1::shared_ptr;

shared_ptr<int> sp1(new int(1));

shared_ptr<int> sp2(sp1);
shared_ptr<int> sp3(wp1);

Custom deleter constructor with custom deleter:


struct deleter
{
void operator()(Ty *ptr) const
{
    // delete ptr;        
}       
};

shared_ptr<int> sp4(new int(4),deleter());

Member function get_deleter:


template <class D, class ty>
D *get_deleter(const shared_ptr<Ty> &sp);

Member function reset:


sp3.reset();
sp1.reset(rp1);
sp1.reset(rp1, deleter());

Member function swap (also available as free-function):


sp2.swap(sp1);
swap(sp1,sp2);

Member function operator */-> member function operator*:


Ty &operator*() const;
*sp1.member();

Member function operator->:


Ty *operator->() const;
sp1->member();

Member function get:


Ty *get() const;

Member function use_count:


long use_count() const;

Member function unique:


bool unique() const;
sp.unique();

Member function operator boolean-type: ( get() == 0 )


operator boolean-type() const;
if (sp) { ... }

shared_ptr<int> sp1;
shared_ptr<int> sp2( reinterpret_cast<int *>(0));
shared_ptr<int> sp3( new int(0) );

static_cast<bool>(sp1) ->false
static_cast<bool>(sp2) ->false
static_cast<bool>(sp3) ->true

Member function operator=():


shared_ptr &operator=(const shared_ptr &sp);
sp1=sp2;

Comparisons operator== / operator<


sp1 == sp2

note: equiv does distinguish between default-constructed sp1 and sp2 constructed with a NULL pointer, while opearator== does not.

template <class Ty1, class Ty2>
bool
equiv
(shared_ptr<Ty1> lh, shared_ptr<Ty2> rh)
{
   return !(lh < rh) && !(rh < lh);
}

enable_shared_from_this class template:


class Test : public enable_shared_from_this <Test>
{
    ...
    
    shared_ptr<Test> 
    get_ptr 
    {
         ... 
        return this->shared_from_this();
    }
  
};  


shared_ptr<Test> sp1 (new Test);
...
Test  *raw = sp1.get();
...
shared_ptr<Test> sp2 (raw->get_ptr());

assert( sp1.get() == sp2.get() );
assert( sp1.use_count() == 2 );

Cast conversions:


template <class Ty, class O>
shared_ptr<Ty> static_pointer_cast(const shared_ptr<O> &sp);

template <class Ty, class O>
shared_ptr<Ty> dynamic_pointer_cast(const shared_ptr<O> &sp);

template <class Ty, class O>
shared_ptr<Ty> const_pointer_cast(const shared_ptr<O> &sp);


Comments