Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a boost::shared_ptr to NULL

Tags:

c++

boost

Can I initialize shared_ptr with NULL value?

boost::shared_ptr<Type> s_obj(NULL);

If not, then how?

like image 317
domlao Avatar asked Apr 26 '13 05:04

domlao


People also ask

Can a shared_ptr be null?

A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .

What is an empty shared_ptr?

Empty shared_ptr can be constructed with default constructor or with constructor that takes nullptr . Non-empty null shared_ptr has control block that can be shared with other shared_ptr s. Copy of non-empty null shared_ptr is shared_ptr that shares the same control block as original shared_ptr so use count is not 0.

Is null and Nullptr the same?

Nullptr vs NULLNULL is 0 (zero) i.e. integer constant zero with C-style typecast to void* , while nullptr is prvalue of type nullptr_t , which is an integer literal that evaluates to zero.


2 Answers

The default construction does this for you:

template<class T> class shared_ptr
{
public:

    explicit shared_ptr(T * p = 0): px(p)
    { 
        //Snip
    }

    //...

private:

    T * px;            // contained pointer
    count_type * pn;   // ptr to reference counter
};
like image 186
Yuushi Avatar answered Oct 18 '22 00:10

Yuushi


That's the default construction, i.e.:

boost::shared_ptr<Type> s_obj;

s_obj now holds a null pointer and evaluates to boolean false when truth-tested;

like image 39
W.B. Avatar answered Oct 18 '22 00:10

W.B.