Consider the two cases:
Object& obj = *getObjectPtr();
Object obj = *getObjectPtr();
What is the difference between these two in C++?
Consider the two cases:
Object& obj = *getObjectPtr();
Object obj = *getObjectPtr();
What is the difference between these two in C++?
Line (1) is semantically equivalent to Object *obj_p = getObjectPtr()
, and then using *obj_p
. The reference behaves like a pointer, but without pointer syntax. More examples here: http://en.wikipedia.org/wiki/Reference_%28C++%29
Line (2) will cause a new Object
to be created, and the Object
at the memory address getObjectPtr()
to be copied into it via (probably) Object
's copy constructor.
Object& obj = *getObjectPtr();
- obj will hold a reference to the original object that is returned by getObjectPtr()
.
Object obj = *getObjectPtr();
- obj will hold a copy of the original object that is returned by getObjectPtr()
.