c++ - What is shared_ptr's aliasing constructor for? -
in page (http://www.cplusplus.com/reference/memory/shared_ptr/), paragraph 5, says:
additionally, shared_ptr objects can share ownership on pointer while @ same time pointing object. ability known aliasing (see constructors), , commonly used point member objects while owning object belong to. because of this, shared_ptr may relate 2 pointers:
a stored pointer, pointer said point to, , 1 dereferences operator*.
an owned pointer (possibly shared), pointer ownership group in charge of deleting @ point, , counts use.
generally, stored pointer , owned pointer refer same object, but alias shared_ptr objects (those constructed alias constructor , copies) may refer different objects.
then read page (http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/) aliasing constructor of shared_ptr. still think "aliasing" behavior confusing. why here? for? in situation want feature?
simple example:
struct bar { // data want point }; 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 object pointed f 2 f.reset(); // foo still exists (ref cnt == 1) // our bar pointer still valid, , can use stuff some_func_that_takes_bar(specific_data);
aliasing when want point bar
, don't want foo
deleted out under us.
as johannes points out in comments, there equivalent language feature:
const bar& specific_data = foo(...).bar;
we're taking reference member of temporary, temporary foo
still kept alive long specific_data
is. shared_ptr
example, have bar
lifetime tied foo
- foo
cannot access.
Comments
Post a Comment