Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Pointer to Reference, Costly? [duplicate]

Tags:

c++

c++11

Possible Duplicate:
How expensive is it to dereference a pointer in C++?

If I've got a pointer to an object, let's say Object *ptr;, and I want to pass that to a method of the form void foo(Object& obj) I understand that I need to write:

foo(*ptr);

But why dereference ptr? Wouldn't it make sense to just pass it foo(ptr);? I'm worried *ptr might be making a copy of the original object, or at the least not merely passing to foo the address to work with.

Can anyone clear this up for me? Is passing *ptr a potential bottleneck, for code that expects this to behave just as fast as if the function had been void foo(Object *obj); and called via foo(ptr)?

like image 309
Mr. Smith Avatar asked Jan 07 '13 10:01

Mr. Smith


2 Answers

I'm worried *ptr might be making a copy of the original object.

You're wrong. Dereferencing a pointer doesn't make any copy!

void f(Object & obj); //note it takes the argument by reference

Object *ptr = get();

foo(*ptr); 

At the last line of this code there is no copy. The Standard gives you that guarantee.

However, if f takes the argument by value, then there will be copy.

The bottomline: the reference in the function parameter is used to avoid copy (often) or as ouput parameter (occasionally)!

like image 193
Nawaz Avatar answered Oct 24 '22 15:10

Nawaz


Passing an object by reference just passes the pointer so foo(*ptr) is correct and won't copy the object. Why dereference it? Because the function signature wants an object, not a pointer to an object. C++ is a strongly typed language.

like image 35
TheMathemagician Avatar answered Oct 24 '22 15:10

TheMathemagician