Reputation: 9502
How to get a reference to an object having shared_ptr<T>
to it? (for a simple class T
)
Upvotes: 20
Views: 18963
Reputation: 48794
Is there a concept of shared refrence?
Yes actually! shared_ptr
provides an "aliasing constructor" that can be used exactly for this purpose. It returns a shared_ptr
that uses the same reference count as the input shared_ptr
but points to a different reference, typically a field or value derived from the backing data.
It is the responsibility of the programmer to make sure that this
ptr
remains valid as long as this shared_ptr exists, such as in the typical use cases whereptr
is a member of the object managed byr
or is an alias (e.g., downcast) ofr.get()
What is shared_ptr's aliasing constructor for? goes into this in more detail, including an example of how to use it.
Upvotes: 0
Reputation: 33437
operator*
already returns a reference:
T& ref = *ptr;
Or, I suppose I could give a more meaningful example:
void doSomething(std::vector<int>& v)
{
v.push_back(3);
}
auto p = std::make_shared<std::vector<int>>();
//This:
doSomething(*p);
//Is just as valid as this:
vector<int> v;
doSomething(v);
(Note that it is of course invalid to use a reference that references a freed object though. Keeping a reference to an object does not have the same effect as keeping a shared_ptr instance. If the count of the shared_ptr instances falls to 0, the object will be freed regardless of how many references are referencing it.)
Upvotes: 22