shared_ptr的和use_count(shared_ptr and use_count)

2019-09-21 03:35发布

在下面的代码片段:

shared_ptr<int> p;

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

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

输出出来是

1
1

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

Answer 1:

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

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



Answer 2:

 #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


Answer 3:

从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它释放的最后结构。



文章来源: shared_ptr and use_count