gpt4 book ai didi

c++ - shared_ptr 的别名构造函数有什么用?

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:18 27 4
gpt4 key购买 nike

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

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.

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 的别名构造函数。但我仍然认为这种“别名”行为令人困惑。 为什么会在这里?它是做什么用的?在什么情况下我需要此功能?

最佳答案

简单的例子:

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 从我们下面删除。


正如 Johannes 在评论中指出的那样,有某种等效的语言功能:

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

我们引用了一个临时成员,但是只要 specific_data 存在,临时 Foo 就仍然存在。对于 shared_ptr 示例,我们有一个 Bar,它的生命周期与 Foo - Foo 相关联我们无法访问。

关于c++ - shared_ptr 的别名构造函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com