Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 764
wrongusername Avatar asked Dec 14 '10 07:12

wrongusername


People also ask

What happens when you dereference a pointer?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.

What does dereference operator will return?

In computer programming, a dereference operator, also known as an indirection operator, operates on a pointer variable. It returns the location value, or l-value in memory pointed to by the variable's value. In the C programming language, the deference operator is denoted with an asterisk (*).

What happens when one tries to dereference a pointer to null?

Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.


2 Answers

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.

like image 102
Goz Avatar answered Sep 17 '22 09:09

Goz


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.

like image 35
MSalters Avatar answered Sep 19 '22 09:09

MSalters