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)
?
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)!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With