> do you suggest we should rely on this and simply store the return value
> as a new object even if the function returns a reference?
In general, I strongly favour value semantics. If possible, a function should return a value instead of a reference, and for a function which returns reference, the result should be stored as a value.
There are many (typical) exceptions to this approach; for instance a library written with high performance as an overriding design goal would leave the copying, if any, to be done by the client of the library.
> If you pass the object by reference to an external function, that the compiler don't know the implementation of,
> the compiler would have to create a copy just so that the object can be passed to that function.
Yes. Also, if the implementation of the function returning the reference is unknown.
For instance, in the earlier example, if we change the class to this:
1 2 3 4 5 6 7 8 9 10 11 12
|
struct A
{
A() = default ;
A( const A& that ) : data(that.data) { maybe_observable_behaviour() ; }
// ...
int data {} ;
char filler[12] {} ;
// function with unknown implementation: it may have observable side effects
void maybe_observable_behaviour() ; // note: not const-qualified
};
|
https://godbolt.org/g/Tng8k6
Unless link-time optimisation/code generation is enabled.