Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to an object having shared_ptr to it?

Tags:

c++

shared-ptr

How to get a reference to an object having shared_ptr<T> to it? (for a simple class T)

like image 903
myWallJSON Avatar asked Nov 27 '12 00:11

myWallJSON


1 Answers

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

like image 89
Corbin Avatar answered Oct 28 '22 15:10

Corbin