(new int(42)); std::" /> (new int(42)); std::" /> (new int(42)); std::"/>

Does the temporary of a smart pointer have a reference count, or if so, does it insrement its reference count?

55 views Asked by At

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?

1

There are 1 answers

0
pptaszni On

Yes, the temporary shared_ptr has a reference count. However, in your example there is no temporary, this line auto 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:

std::shared_ptr<int> p1{new int(1)};
std::cout << p1.use_count() << std::endl;  // prints 1
std::cout << std::shared_ptr<int>(p1).use_count() << std::endl;  // prints 2, because you made a temporary copy of your original ptr
std::cout << p1.use_count() << std::endl;  // prints 1 again, temporary was destroyed