什么是shared_ptr的别名构造函数? [英] What is shared_ptr's aliasing constructor for?

查看:852
本文介绍了什么是shared_ptr的别名构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此页面( http://www.cplusplus.com/reference/memory/shared_ptr/ ) ),第5段,它说:

In this page (http://www.cplusplus.com/reference/memory/shared_ptr/), paragraph 5, it says:


此外,shared_ptr对象可以共享指针的所有权,同时指向另一个对象。此能力称为别名(请参阅构造函数),通常用于在拥有它们所属的对象时指向成员对象。因此,shared_ptr可以涉及两个指针:

Additionally, shared_ptr objects can share ownership over a pointer while at the same time pointing to another object. This ability is known as aliasing (see constructors), and is commonly used to point to member objects while owning the object they belong to. Because of this, a shared_ptr may relate to two pointers:


  • 存储的指针,它是指向它的点

  • A stored pointer, which is the pointer it is said to point to, and the one it dereferences with operator*.

拥有的指针(可能是共享的),它是所有权组负责删除的指针。

An owned pointer (possibly shared), which is the pointer the ownership group is in charge of deleting at some point, and for which it counts as a use.

通常,存储的指针和拥有的指针指向相同的对象但别名shared_ptr对象(使用别名构造函数及其副本构造的对象)可能引用不同的对象

Generally, the stored pointer and the owned pointer refer to the same object, but alias shared_ptr objects (those constructed with the alias constructor and their copies) may refer to different objects.

然后,我阅读此页面( http://www.cplusplus.com/reference/memory/ shared_ptr / shared_ptr / )关于shared_ptr的别名构造函数。但我仍然认为这种混叠行为混乱。 为什么会出现在这里?它是什么?

Then I read this page (http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/) about the aliasing constructor of shared_ptr. But I still think this "aliasing" behavior confusing. Why is it here? What is it for? In what situation would I want this feature?

推荐答案

简单示例:

struct Bar { 
    // some data that we want to point to
};

struct Foo {
    Bar bar;
};

shared_ptr<Foo> f = make_shared<Foo>(some, args, here);
shared_ptr<Bar> specific_data(f, &f->bar);

// ref count of the object pointed to by f is 2
f.reset();

// the Foo still exists (ref cnt == 1)
// so our Bar pointer is still valid, and we can use it for stuff
some_func_that_takes_bar(specific_data);

别名是为了当我们真的想指向 Bar ,但我们也不想让 Foo 从我们下面删除。

Aliasing is for when we really want to point to Bar, but we also don't want the Foo to get deleted out from under us.

正如Johannes在评论中指出的,有一个等同的语言功能:

As Johannes points out in the comments, there is a somewhat equivalent language feature:

Bar& specific_data = Foo(...).bar;

我们引用临时的成员,但临时 Foo 仍然保持有效,只要 specific_data 是。与 shared_ptr 示例一样,我们有一个 Bar ,其生命周期与 Foo - a Foo ,我们无法访问。

We're taking a reference to a member of a temporary, but the temporary Foo is still kept alive as long as specific_data is. As with the shared_ptr example, what we have is a Bar whose lifetime is tied to a Foo - a Foo that we cannot access.

这篇关于什么是shared_ptr的别名构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆