Query on use_count of shared pointer | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Query on use_count of shared pointer

Hi Refer code below: https://www.sololearn.com/compiler-playground/cnwgbEXzqv7E I have a confusion on last line's output. Pointer printed is correct as it is matching with pObj2 raw pointer. Then why count is still 2? Isn't it expected to be 1? https://code.sololearn.com/cnwgbEXzqv7E/?ref=app

3rd Sep 2023, 7:53 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 3
your expectation is wrong. there are two shared_ptr objects to the "clsTest(2)" : 1- the assignment to "m_pObj" inside "setReportee" method. 2- a temporary created by the calling method "getReportee". // the temporary is destroyed at the of the calling method and ref count decremented to 1. here is an example : https://www.sololearn.com/compiler-playground/cqThQoTLtCI2
3rd Sep 2023, 12:00 PM
MO ELomari
+ 2
Thanks. I am getting count as 1 if shared_ptr<clsTest> getReportee() Is changed to shared_ptr<clsTest>& getReportee()
3rd Sep 2023, 12:28 PM
Ketan Lalcheta
Ketan Lalcheta - avatar