I have watched a talk (exact timestamp, not explained by him) by Nicolai Josuttis (member of C++ standard committee) and he stated that ever since C++11, getters should be written like so:
const std::string& getName() const&
{
return memberStringVar;
}
The question is, what is the difference comparing to this getter?
const std::string& getName() const
{
return memberStringVar;
}
In the example given in the talk, there are two overloads of
getName()given. One with the&&and the other with theconst&qualifiers.Without the
&after theconst, the functionconst std::string& getName() constcannot be overloaded with the overload for rvaluesstring Customer::getName() &&.You would then have to remove the rvalue overload from the code completely if you want it to work.
Since ref qualified member functions were added only in C++11 (making the getter for rvalues possible), the change from
const std::string& getName() consttoconst std::string& getName() const&was needed to make both overloads possible.The C++17 standard draft n4659 states :
Since there is one overload of
getName()with a ref-qualifier (&&), the other one also should have the ref qualifier. This is whyconst&is required.