For example we have encoding function. What is the best practice to use:
void Crypto::encoding(string &input, string &output)
{
//encoding string
output = encoded_string;
}
or
string Crypto::encoding(string &input)
{
//encoding string
return encoded_string;
}
Should we use reference or return for returning the string? As far as I know returning a string will take some time to initialize a new string that will be returned by return instruction. When working on a referenced variable I don`t waste time to initialize some new variable I just end the function.
Should we mostly use reference and make function return type void? Or we should only return data by reference when we want to return two or more variables and when we need return one variable then use return instruction?
The major advantage of return by address over return by reference is that we can have the function return nullptr if there is no valid object to return.
The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable. Functions in C++ can return a reference as it's returns a pointer. When function returns a reference it means it returns a implicit pointer.
C# always returns by value*. However, in C# most types are reference types, which means any variable of that type is a reference; and it is that reference which is returned by value.
When you pass a value-type parameter to a function by value, it means that the changes you make to that parameter inside the function will only be affected while inside that function. There will be no effect on the original data that is stored in the argument value.
Do not optimize what you did not measure.
Usually it is better (more readable) to return the result of your computation with return
. If this takes to long because the object is too fat, you can still revert to return your result via reference parameters, but only after you proved that this will result in significant improvement of performance (measure it). E.g if you only ever encode very short strings and only do that once in a while, the overhead of copying is negligible.
Copying things are usually eliminated since most modern compilers have RVO features. You can take the benefits even without c++11.
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