Does dereferencing a pointer make a copy of it?

wrongusername picture wrongusername · Dec 14, 2010 · Viewed 12.8k times · Source

Does dereferencing a pointer and passing that to a function which takes its argument by reference create a copy of the object?

Answer

Goz picture Goz · Dec 14, 2010

In this case the value at the pointer is copied (though this is not necessarily the case as the optimiser may optimise it out).

int val = *pPtr;

In this case however no copy will take place:

int& rVal = *pPtr;

The reason no copy takes place is because a reference is not a machine code level construct. It is a higher level construct and thus is something the compiler uses internally rather than generating specific code for it.

The same, obviously, goes for function parameters.