+ 2
Question on structure in cpp
in the function definition below Distance &sum(Distance l1, Distance l2) what does & do in it. if it is call be reference it should be &l1,&l2 why it is &sum Note Distance is a structure. plz help
5 Réponses
+ 2
It's not &sum, it's Distance&.
It means return Distance by reference.
The l1 and l2 are still taken by copy.
Be aware that this can easily lead to undefined behaviour if you don't know what you're doing.
For example you could construct a Distance on the stack inside sum and return that, because the returned value would be destroyed by the time it returned it's undefined behaviour.
+ 2
Well, take a function like swap( int& a, int& b ) a call by reference.
Which takes the memory address of the variables passed to it and is then able to modify them.
So the variables used when calling the function are the same as those used inside the function.
This modification is then reflected outside the function because they ( the variables used when calling the function ) share the same memory address.
If this was a call by value then an entirely new int would be constructed in memory, resulting in a different memory address.
So now the variables used to call the function are different from the ones used inside the function.
The function would then edit this different memory and the change wouldn't be reflected outside the function.
Returning a reference from a function works the exact same way.
+ 1
I didn't understand plz explain in detail
+ 1
Which part don't you understand? The reference part or the undefined behaviour part?
+ 1
reference part