I have a question while reading "Section 12.1" of "C++ Primer 5th". It can be described as followed:
auto p = std::shared_ptr<int>(new int(42));
std::cout << p.use_count() << std::endl;
The output will be "1" which means there is only one shared_ptr refers to the object. But the "counter" associated with a shared_ptr will be incremented when used as the right-hand operand of an assignment(Page 452, Line 4 of C++ Primer 5th). As a result, if temporary std::shared_ptr<int>(new int(42)) has a counter, it will increment its counter to 2 after used as the right-hand operand of an assignment. I don't know the details of the implementation of smart pointers, does the temporary of a smart pointer have a reference count? If so, does it inscrement its reference count?
Yes, the temporary
shared_ptrhas a reference count. However, in your example there is no temporary, this lineauto p = std::shared_ptr<int>(new int(42));just calls a constructor. If you want to observe reference count being increased and decreased by creation of temporary copy, you can do: