Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can we call reset on null shared_ptr?

The C++ primer shows an example:

        auto &nos = result[word]; 
        if (!nos) nos.reset(new std::set<int>);

Where result is std::map<string, shared_ptr<std::set<int>>>.

My question is: if !nos holds, is nos null? then why can we call reset method on this null shared_ptr?

like image 457
chenzhongpu Avatar asked Sep 05 '25 17:09

chenzhongpu


1 Answers

Yes, it's null, in the it doesn't point to any data sense, but it's still a valid shared_ptr object. In the example code, you re-set it with a valid pointer.

Alternatively, you could write this:

auto &nos = result[word]; 
if (!nos) nos = std::make_shared<std::set<int>>();
like image 81
krzaq Avatar answered Sep 09 '25 00:09

krzaq