> when returning just a type, a reference to a type, or a const reference to a type is sufficient/required/mandatory.
In general, favour value semantics; favour pass by value and returning values.
This is particularly true for object-oriented interfaces.
1 2 3 4 5 6 7 8
|
struct book
{
virtual ~book() = default ;
virtual const std::string& title() const = 0 ; // implementation in disguise
virtual std::string author() const = 0 ; // fine: fully encapsulates implementation
};
|
There are situations where value semantics is impossible; for instance, return an object of a polymorphic type, or pass a non-copyable, non-moveable object.
Sometimes, passing by reference or returning an object (an
lvalue reference) is required; for instance the identity of the object is important.
Though this has become less common after C++11, we may want to use references in order to avoid the expensive copy of an object. This is usually true in generic code where the type of the object could be anything.
As far as the
const qualifier is concerned, on
lvalues, use
const pro-actively - if it can be
const, make it
const.
Avoid const-qualifying
prvalues.