C ++ returns objects by value

The topic is largely about the title of the question. I saw this in Meires' book Effective C ++:

the fact that C ++ returns objects by value

What does this mean and how does the C ++ standard support this post? For instanance, let's say we have something like this:

int foo()
{
    int a = 1;
    return a;
}

      

This is pretty clear, the phrase will mean that we will return a copy of the value stored in the local variable. But consider the following:

int& foo()
{
    int a = 1;
    return a;
}

      

The compiler should warn us about returning a reference to a local variable. How does this "return by fact" apply to this example?

+3


source to share


3 answers


Meyers is correct in the main, although you must accept this formulation with a pinch of salt when working with links. At a certain level of abstraction, here you are passing a reference by value.

But what he is really trying to say is that, in addition, C ++ is the default by default, and that this contrasts with languages ​​like Java, in which objects are always thrown with reference semantics.



In fact, it could be argued that this passage does not apply to your code at all, because the link is not an "object".

+6


source


When the book says "C ++ returns objects by value", it explains what happens when you use a "simple" class name as the return type, without additional "embellishments" such as ampersands or asterisks, for example.

struct MyType {
    ... // Some members go here
};
MyType foo() {
    ...
}

      

The above example foo()

returns an object by value.



This quote should not suggest that there are no other ways to return data from a function in C ++: as you can easily construct a function that returns a reference or pointer.

Note that returning an object by pointer or by reference creates undefined behavior only when you return a pointer or reference to a local object. Accessing an object during its lifetime always invokes undefined behavior. Returning local by reference or pointer is arguably the most common error that causes this undefined behavior.

+2


source


Returning by reference will give you an error, since u is passing a variable reference to another function (the function that calls the foo function) that is outside that local variable (the a variable).

0


source







All Articles