wrongusername
wrongusername

Reputation: 18918

Does dereferencing a pointer make a copy of it?

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

Upvotes: 53

Views: 21295

Answers (4)

Goz
Goz

Reputation: 62333

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.

Upvotes: 47

MSalters
MSalters

Reputation: 179981

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.

Upvotes: 10

icecrime
icecrime

Reputation: 76805

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.

Upvotes: 5

hmuelner
hmuelner

Reputation: 8231

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.

Upvotes: 3

Related Questions