返回shared_ptr时的引用计数

Ton*_*ion 5 c++ smart-pointers

以下代码是否表示当此函数返回时,此类中的请求对象仍保留对此对象的引用?

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

用过的:

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

即使在完成上述任务后,我们仍然有两个参考request...

其中request只是一个RequestList指针(原始指针)......

Pot*_*ter 5

请求是私有类变量...

然后有两个shared_ptr带有句柄的对象new Request():调用函数和私有类变量.两者都合法地破坏了引用计数.

除非存在私有类变量的原因,否则将其消除.至少,重命名它last_request,因为它就是它的真实含义.

(当然,当last_request被另一个调用重新分配时GetRequest,它对前一个请求的处理就会消失.)


ybu*_*ill 1

返回时有两个,语句末尾有一个。

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

所以当它返回时它是 2 因为有一个临时的。

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

当然你可以用来request.use_count()获取引用计数。