Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Returning by Reference Useless?

Tags:

c++

Coming from a C# background, I was more or less puzzled by the seemly weird behavior of returning method handling in C++. My concern now is for a method in C++, returning by reference is not a very useful technique, this is because-- unlike C#--any variable declared inside a method body will go out of scope once the the control exit the method.

So, in C++, this cannot even compile ( but an equivalent version in C# can):

int& DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // return a reference to nValue here
} // nValue goes out of scope here

The only time where returning by reference is useful is when you are returning a reference to an existing data member in a class, or you are returning a reference to an element inside a parameter of the method. But in both cases there is really no need to return anything; as the returned reference is already freely available to the caller of the method.

So, my conclusion is, there is no need to use return by reference at all. Am I right?

like image 330
Graviton Avatar asked Jan 24 '11 03:01

Graviton


People also ask

Why should we return by reference?

Functions can be declared to return a reference type. There are two reasons to make such a declaration: The information being returned is a large enough object that returning a reference is more efficient than returning a copy. The type of the function must be an l-value.

When should we return by reference?

A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.

What does return by reference mean?

If you return it by reference, you are returning an alias to that same variable. If you pass it to another method by reference, you are passing a reference to the variable it aliases. When you make a ref local alias, you make a new alias to the same variable.

Does C++ return by value or reference?

C++ functions can return by value, by reference (but don't return a local variable by reference), or by pointer (again, don't return a local by pointer). When returning by value, the compiler can often do optimizations that make it equally as fast as returning by reference, without the problem of dangling references.


1 Answers

Operations like std::vector<>::operator[] return references to elements obtained by dereferencing a pointer (and adding offsets to it). The pointer in that case is a private member internal to the vector, and so not something the user could have obtained themselves without breaking the abstraction of the class.

like image 100
Jeremiah Willcock Avatar answered Sep 29 '22 15:09

Jeremiah Willcock