在此页面(http://www.cplusplus.com/reference/memory/shared_ptr/)第5段中,它说:
此外,shared_ptr对象可以在指向另一个对象的同时共享指针的所有权.此功能称为别名(请参阅构造函数),通常用于指向成员对象,同时拥有它们所属的对象.因此,shared_ptr可能与两个指针有关:
存储指针,它是指向它的指针,以及它与运算符*取消引用的指针.
一个拥有的指针(可能是共享的),它是所有权组在某个时刻负责删除的指针,并且它被视为一个用途.
通常,存储的指针和拥有的指针引用相同的对象,但是别名shared_ptr对象(使用别名构造函数及其副本构造的对象)可以引用不同的对象.
然后我读了这页(http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/)关于shared_ptr的别名构造函数.但我仍然认为这种"走样"行为令人困惑.为什么在这里?它是为了什么?在什么情况下我想要这个功能?
Bar*_*rry 47
简单的例子:
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);
Run Code Online (Sandbox Code Playgroud)
别名是我们真正想要指出的时候Bar
,但我们也不希望Foo
从我们这里删除.
正如约翰内斯在评论中指出的那样,有一个相当的语言特征:
Bar const& specific_data = Foo(...).bar;
Bar&& also_specific_data = Foo(...).bar;
Run Code Online (Sandbox Code Playgroud)
我们正在引用一个临时成员,但暂时Foo
仍然保持活着specific_data
.如同shared_ptr
例子,我们有什么是Bar
它的生命周期被绑定到一个Foo
-一个Foo
我们无法访问.
归档时间: |
|
查看次数: |
6994 次 |
最近记录: |