shared_ptr和use_count

时间:2012-08-12 08:01:30

标签: c++ shared-ptr

在以下代码段中:

shared_ptr<int> p;

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

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

输出结果为

1
1

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

3 个答案:

答案 0 :(得分:5)

 #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

答案 1 :(得分:4)

临时对象的生命周期不会持续足够长的时间让第一个p.use_count()返回2.临时对象首先被销毁,放弃对其拥有的任何东西的所有权。

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

答案 2 :(得分: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.

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