3

在以下代码片段中:

shared_ptr<int> p;

{
    p = shared_ptr<int>(new int);
    cout<<p.use_count()<<endl;
}

cout<<p.use_count()<<endl;

输出结果是

1
1

我不明白为什么第一个输出是1- 不应该2吗?

4

3 回答 3

8

临时对象的生命周期不足以使第一个p.use_count()返回 2。临时对象首先被销毁,放弃它对​​它所拥有的任何东西的所有权。

此外,由于临时值是右值,分配到p将导致移动分配,这意味着使用计数永远不会是 2(假设实现质量)。所有权只是简单地从临时转移到p,从不超过 1。

于 2012-08-12T08:17:54.270 回答
6
 #include <memory>
 #include <iostream>

 int
 main(int argc, char** argv) {
   std::shared_ptr<int> p(new int);
   std::shared_ptr<int> p2(p);
   std::cout << p.use_count() << std::endl;
   return 0;
 }

output: 2

解释/编辑:在您的来源中,最初的“p”从未拥有任何东西的所有权。在对 p 的第二次引用中,您分配给一个临时的并且基本上放弃了对“p”的所有权。最有可能的是,移动构造函数也用于满足此分配。

编辑:这可能是你想要的?

 #include <memory>
 #include <iostream>

 int
 main(int argc, char** argv) {
   std::shared_ptr<int> p(new int);
   {
       std::shared_ptr<int> p2(p);
       std::cout << p.use_count() << std::endl;
   }
   std::cout << p.use_count() << std::endl;
   return 0;
 }

output: 2
        1
于 2012-08-12T08:11:35.893 回答
1

来自 boost.org:

template<class Y> explicit shared_ptr(Y * p); 
Requirements: p must be convertible to T *. Y must be a complete type. The     expression delete p must be well-formed, must not invoke undefined behavior, and     must not throw exceptions.

Effects: Constructs a shared_ptr that owns the pointer p.

Postconditions: use_count() == 1 && get() == p.

Throws: std::bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.

Exception safety: If an exception is thrown, delete p is called.

Notes: p must be a pointer to an object that was allocated via a C++ new    expression or be 0. The postcondition that use count is 1 holds even if p is 0;    invoking delete on a pointer that has a value of 0 is harmless.

如您所见,如果您从新的 int 构造一个新的 shared_ptr,它会释放最后一个构造。

于 2012-08-12T08:15:24.347 回答