首页 > 解决方案 > std::shared_ptr 的“拥有的指针”和“存储的指针”有什么区别?

问题描述

根据这个文档,它说(强调我的):

http://www.cplusplus.com/reference/memory/shared_ptr/owner_before/

与 operator< 重载不同,此排序考虑了shared_ptr 拥有的指针,而不是存储的指针,因此这些对象中的两个被认为是等效的(即,无论操作数的顺序如何,此函数都返回 false),如果它们两者共享所有权,或者它们都是空的,即使它们存储的指针值不同。

如果 shared_ptr 对象是别名(别名构造的对象及其副本) ,则存储的指针(即 shared_ptr 对象取消引用的指针)可能不是拥有的指针(即,在对象销毁时删除的指针)。

的“拥有的指针”和“存储的指针”有什么区别std::shared_ptr

对于这个问题,我将不胜感激。

这是一些相关代码(检查http://cpp.sh/27auqq):

// enable_shared_from_this example
#include <iostream>
#include <memory>

struct C : std::enable_shared_from_this<C> {int a; int b; };

int main () {
  std::shared_ptr<C> foo, bar;

  foo = std::make_shared<C>();

  bar = foo->shared_from_this();
  
  std::shared_ptr<int> p1(foo, &foo->a);
  std::shared_ptr<int> p2(foo, &foo->b);
  
  *p1=5;
  *p2=9;
  
  std::cout << p1.use_count() << std::endl;
  std::cout << foo->a << std::endl;
  std::cout << foo->b << std::endl;

  if (!foo.owner_before(bar) && !bar.owner_before(foo))
    std::cout << "foo and bar share ownership" << std::endl;
    
  if(!p1.owner_before(p2) && !p2.owner_before(p1))
    std::cout << "p1 and p2 share ownership" << std::endl;
    
    if(!p1.owner_before(foo) && !foo.owner_before(p1))
    std::cout << "p1 and foo share ownership" << std::endl;
      

  return 0;
}

这是输出:

4
5
9
foo and bar share ownership
p1 and p2 share ownership
p1 and foo share ownership

标签: c++c++11shared-ptr

解决方案


“拥有的指针”和“存储的指针”有什么区别std::shared_ptr

每当您使用构造函数template< class Y > shared_ptr::shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;时,您都会拥有与 共享所有权r但取消引用的东西*ptr

例如之后

std::shared_ptr<std::pair<int, double>> pair = std::make_shared<std::pair<int,double>>(1, 2.);
std::shared_ptr<int> i(pair, &pair->first);
pair.reset();

std::pair<int, double>i


推荐阅读