Reputation: 8678
In this article its says that references allow you to reduce the amount of copying behind the scenes. Does reference reduce any other operation compared to a variable?
Upvotes: 1
Views: 365
Reputation: 8904
No. Savings apply only to copying esp.when passing as argument to function and return value from the function.
Upvotes: 0
Reputation: 10917
On most compiler, references are implemented using pointers, and thus, have the same exact costs as those that would have been implied if you were using a pointer instead of a reference.
Note that the standard does not force implementation of references to rely on pointers. In particular
It is unspecified whether or not a reference requires storage (3.7).
References allow you to pass arguments "by reference", as opposed to "passed by copy".
void f(int & r) { r = 1; }
void g(int const * p) { *p = 2; }
void h(int j) { j = 3; }
int main()
{
int i = 0;
f(i); // i now equals 1
g(&i); // i now equals 2 (the address of i was given to g)
h(i); // i is copied and thus not modified (ie i == 2 after this line)
}
See also C++ faqlite: references.
Upvotes: 1
Reputation: 189
To answer your exact question, passing by reference only does one thing: it allows you to pass a variable into a function instead of a copy of that variable.
Depending on when this is used, the implications are huge. But that's the most basic answer I can think of to get you started.
Edit: I saw your concern was speed. It is always strongly recommended to pass by reference whenever it is an option, because the speed savings can be huge, especially when some huge class/struct is being passed into a function.
Upvotes: 0
Reputation: 1475
If you are concerned about memory usage, just think of passing by reference as passing by value with a pointer, with the dirty work done behind the scenes. The amount of memory used by the pointer depends on the platform/OS.
Upvotes: 0
Reputation:
The idea of a reference as a variable like this:
const int & r = 42;
is basically wrong. OK, you can create such things, but what references were originally designed for was to facilitate passing objects to functions and (to a lesser extent) returning them from functions. If you use them in any but these two contexts, unless you are much, much cleverer than me, or most other programmers, you are doing it wrong.
Upvotes: 0
Reputation: 20272
Reference is a kind of a variable. You're asking about passing by reference instead of passing by value.
Passing by value creates a copy of the value being passed, while passing by reference means that the receiver will be able to change that same variable whose value you passed.
Both have its own benefits and shortcomings, and should be used when appropriate (for example, by reference would be used sometimes to save on copy operations or get return values, while by value would be used to pass data which shouldn't be locally changed but will be changed inside the called function).
Upvotes: 1