hey, i have a question about returning a reference from functions.
It could be returning member function for classes, regular functions, class helperfunctions etc...
So is returning a reference just to speed up the program?
heres a short example:
1 2 3 4 5 6 7 8 9 10 11
int& x() //what if i didn't have &?
{
int aa = 20;
return aa;
}
int main()
{
int a = x();
return 0;
}
1. Passing primitive types by reference is actually slower than passing them by value
2. In your example, returning by reference does not keep aa alive - aa is destructed and a in main is assigned random memory from where aa used to be in memory.
You shouldn't return a reference in this case. aa is local inside the function and as soon as the function ends it will no longer exist. Line 9 tries to copy a non-existing object.
Big objects are often passed by reference and in some cases returned by reference to avoid copying it. Simple types like int are not costly to copy and passing it by reference is probably slower.
If you return a reference you have to make sure that the object stays alive after the function returns. If you have a member function that returns one of the member variables you can use references, but if you don't want the caller to be able to modify it you should make it a const reference.
You seem to have pointers and references confused.
Pointers:
1 2
int x = 7;
int *y = &x;
References:
1 2 3
int x = 7;
int &y (x);
int &z = x; //alternate form
The reason dude3 does not have the same address is because dude3 is not a reference, it is its own person crated by copying the person returned by reference from get(). I think you meant this:
Hmm ok, but the only difference between returning a reference from the function and not returning reference from the function, is the speed of the program right?
but the only difference between returning a reference from the function and not returning reference from the function, is the speed of the program right?
Hmm ok, but the only difference between returning a reference from the function and not returning reference from the function, is the speed of the program right?
LB wrote:
1. Passing primitive types by reference is actually slower than passing them by value 2. In your example, returning by reference does not keep aa alive - aa is destructed and a in main is assigned random memory from where aa used to be in memory.
Peter87 wrote:
You shouldn't return a reference in this case. aa is local inside the function and as soon as the function ends it will no longer exist. Line 9 tries to copy a non-existing object.
soranz wrote:
Isn't that a great reason to use references ?
Passing primitives by reference is slower than passing them by value. Passing large things by reference, such as vectors and such with many elements, is beneficial.