+ 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 Antworten
+ 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
MO ELomari - avatar
+ 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