In the following code snippet:
shared_ptr<int> p;
{
p = shared_ptr<int>(new int);
cout<<p.use_count()<<endl;
}
cout<<p.use_count()<<endl;
The output comes out to be
1 1
I don’t understand why the 1st output is 1 — shouldn’t it be 2?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The temporary object’s lifetime does not last long enough for the first
p.use_count()to return 2. The temporary object is destroyed first, relinquishing its ownership on anything it owned.Furthermore, since the temporary is an rvalue, the assignment to
pwill result in a move-assignment, which means the use-count will never be 2 anyway (assuming a quality implementation). Ownership is simply transferred from the temporary top, never exceeding 1.