Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is it to dereference a pointer?

Tags:

c++

pointers

How expensive is it to perform the dereference operation on a pointer?

I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.

like image 274
tunnuz Avatar asked Jan 10 '09 18:01

tunnuz


People also ask

What happens when we dereference a pointer?

The dereference operator is also known as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be returned.

How do I dereference a pointer?

Pointers can be dereferenced by adding an asterisk * before a pointer.

Can you dereference a function pointer?

As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call.

What does dereferencing a pointer return?

It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer. That said, we can dereference the pointer without ever accessing the value it points to.


1 Answers

Dereferencing, when translated into machine code, can mean different things depending on what you do with the dereferenced object. Accessing a single member of a class through a pointer is typically cheap. For example if c is a pointer to an instance of class C with an int member n then something like this:

int n = c->n; 

Might translate into one or two machine instructions and might load a register with a single memory access.

On the other hand this implies making a complete copy of the object pointed to by c:

C d = *c; 

The cost of this will depend on the size of C, but note that it is the copy that is the major expense and the 'dereference' part is really just 'using' the pointer address in the copy instructions.

Note that accessing members of large objects typically requires pointer offset calculation and memory access whether or not the object is a local object or not. Typically only very small objects are optimized to live only in registers.

If you are concerned about the cost of pointers over references then don't be. The difference between these are a language semantics difference and by the time the machine code is generated pointer and reference access look exactly the same.

like image 190
CB Bailey Avatar answered Sep 30 '22 04:09

CB Bailey