Reputation: 27445
The topic is pretty much in the title of the question. I saw this in Meyrses book "Effective C++":
the fact that C++ returns objects by value
What does that mean and how the C++ standard supports that message? For instanance, say that we have something like this:
int foo()
{
int a = 1;
return a;
}
That's pretty clear, the phrase would mean that we returns the copy of the value stored in the local variable. But consider this:
int& foo()
{
int a = 1;
return a;
}
A compiler should warn us about returning a reference to a local variable. How does that "returning by value fact" apply to that example?
Upvotes: 3
Views: 223
Reputation: 726987
When the book says that "C++ returns objects by value", it explains what happens when you use a "plain" class name as the return type without additional "decorations", such as ampersands or asterisks, e.g.
struct MyType {
... // Some members go here
};
MyType foo() {
...
}
In the example above foo()
returns an object by value.
This quote should not suggest that C++ lacks other ways of returning data from a function: as you can easily construct a function that returns a reference or a pointer.
Note that returning an object by pointer or by reference creates undefined behavior only when you return a pointer or a reference to a local object. Accessing object past its lifetime always causes undefined behavior. Returning a local by reference or by pointer is perhaps the most common mistake that causes this undefined behavior.
Upvotes: 2
Reputation: 791
Return by reference will give you a error as u are passing a reference of a variable to another function ( function which called function foo) which is beyond the scope of that local variable ( variable a).
Upvotes: 0
Reputation: 385395
Meyers is correct in the main, though you have to take that wording with a pinch of salt when dealing with references. At a certain level of abstraction, here you're passing the reference itself "by value".
But what he's really trying to say is that, beyond that, C++ passes by value by default, and that this contrasts with languages such as Java in which objects are always chucked around with reference semantics instead.
In fact, one could argue that the passage doesn't apply to your code at all, because the reference is not an "object".
Upvotes: 6