Can I initialize shared_ptr with NULL value?
boost::shared_ptr<Type> s_obj(NULL);
If not, then how?
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 .
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.
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.
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
};
                        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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With