boost Smart Pointer

Basic

class Fruit
{
public:
    typedef boost::shared_ptr<Fruit> Pointer; // notice
    typedef boost::shared_ptr<Fruit const> ConstPointer; // notice

    Fruit(int weight)
        : m_Weight(weight)
    {}
private:
    int m_Weight;
};

void Basic()
{
    Fruit::Pointer ptr(new Fruit(1)); // notice
    Fruit * pRaw = ptr.get(); // notice
};

Shared from this

class Fruit
    : public boost::enable_shared_from_this<Fruit> // notice
{
public:
    typedef boost::shared_ptr<Fruit> Pointer;
    typedef boost::shared_ptr<Fruit const> ConstPointer;

    static void PrintWeight(ConstPointer ptr)
    {
        cout << ptr->m_Weight << endl;
    }

    void PrintSelf() const
    {
        PrintWeight(shared_from_this()); // notice
    }
};

Customized Deletor

void CustomizedDeletor()
{
    boost::shared_ptr<FILE> pf(fopen("test.txt", "r"), fclose); // notice
    boost::shared_ptr<void> p(CoTaskMemAlloc(10), CoTaskMemFree); // notice
}
原文地址:https://www.cnblogs.com/frankbadpot/p/1582784.html