Link counter when returning shared_ptr

Does the following code indicate that when returning this function, the request object inside this class still contains a reference to this object?

boost::shared_ptr<Request> RequestList::GetRequest()
{
    boost::mutex::scoped_lock(listmtx);
    request = boost::shared_ptr<Request>(new Request());
    return request;
}

used by:

request = requests->GetRequest();  //Ref count is two on request object when it returns??

even after he completed the above assignment, we still have ref ref for two on request...

where the requests are just a RequestList (raw pointer) ...

+3
source share
3 answers

request is a private class variable ...

Then there are two objects shared_ptrwith a descriptor new Request(): one that is in the calling function and a private class variable. Both are legally recountable.

, . , last_request, .

(, last_request GetRequest, .)

+4

. , -, ( request GetRequest(), , , RequestList, request GetRequest()).

, , , , .

+2

, .

request = boost::shared_ptr<Request>(new Request()); // ref count = 1
return request; // makes a copy of request. ref count = 2

, 2, .

request = requests->GetRequest(); // it two because there is still a temporary
// at the end of the statement all the temporaries are destroyed,
// ref count decremented to 1

Of course, you can use request.use_count()to get a reference count.

+1
source

Source: https://habr.com/ru/post/1768956/


All Articles