Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference or return - best practice [closed]

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?

like image 748
Likon Avatar asked Nov 12 '11 15:11

Likon


People also ask

What is the advantage of returning a reference from the function?

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.

What do you mean by return by reference?

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.

Does C# return by reference or value?

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.

What does it mean to pass a 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.


2 Answers

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.

like image 98
EricSchaefer Avatar answered Oct 05 '22 15:10

EricSchaefer


Copying things are usually eliminated since most modern compilers have RVO features. You can take the benefits even without c++11.

like image 22
Inbae Jeong Avatar answered Oct 05 '22 14:10

Inbae Jeong