Does dereferencing a pointer make a copy of it?

C++PointersDereference

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

In the simple case, no. There are more complicated cases, though:

void foo(float const& arg);
int * p = new int(7);
foo(*p);

Here, a temporary object is created, because the type of the dereferenced pointer (int) does not match the base type of the function parameter (float). A conversion sequence exists, and the converted temporary can be bound to arg since that's a const reference.

Solution 3 - C++

Hopefully it does not : it would if the called function takes its argument by value.

Furthermore, that's the expected behavior of a reference :

void inc(int &i) { ++i; }

int main()
{
    int i = 0;
    int *j = &i;
    inc(*j);
    std::cout << i << std::endl;
}

This code is expected to print 1 because inc takes its argument by reference. Had a copy been made upon inc call, the code would print 0.

Solution 4 - C++

No. A reference is more or less just like a pointer with different notation and the restriction that there is no null reference. But like a pointer it contains just the address of an object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwrongusernameView Question on Stackoverflow
Solution 1 - C++GozView Answer on Stackoverflow
Solution 2 - C++MSaltersView Answer on Stackoverflow
Solution 3 - C++icecrimeView Answer on Stackoverflow
Solution 4 - C++hmuelnerView Answer on Stackoverflow