c++ - 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
解决方案
“拥有的指针”和“存储的指针”有什么区别
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
推荐阅读
- unity3d - 我无法将类定义为 Scriptableobject
- laravel - 在 Laravel 的中间件句柄函数中分配中间件
- swift - 使用 Xcode 在 MacOS 上进行服务器端 Swift 开发,在 Docker Ubuntu 上进行测试:我如何不每次都清理/重新创建?
- c - 警告:从不兼容的指针类型传递“fprintf”的参数 1
- android - 加载数据时显示/隐藏Android进度条
- c++ - 获得 WA,也创建了自己的测试用例,但没有获得批准的答案
- javascript - 如何将 jquery addClass() 方法添加到元素 ng-repeat AngularJS
- c# - 将数据从控制器传递到 Razor 页面,“对象引用未设置为对象实例”的错误
- javascript - 获取浏览器+平台键盘修饰符
- flutter - 屏幕弹出后 Flutter WebviewScaffold 弹出