Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

c++ - What is shared_ptr's aliasing constructor for?

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

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.

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simple example:

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);

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.


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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...