Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getters ending with const and const&

Tags:

c++

getter

I have watched a talk (exact timestamp, not explained by him) by Nicolai Josuttis (member of C++ standard committee) and he stated that getters should be written like so:

const std::string& getName() const&
{
     return memberStringVar;
} 

Ever since C++11. The question is, what is the difference comparing to this getter?

const std::string& getName() const
{
     return memberStringVar;
}
like image 769
Croolman Avatar asked Feb 22 '19 06:02

Croolman


1 Answers

In the example given in the talk, there are two overloads of getName() given. One with the && and the other with the const& qualifiers.

Without the & after the const, the function const std::string& getName() const cannot be overloaded with the overload for rvalues string 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() const to const std::string& getName() const& was needed to make both overloads possible.

The C++17 standard draft n4659 states :

16.1 Overloadable declarations [over.load]
...

2 Certain function declarations cannot be overloaded:
...
(2.3) — Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier.

Since there is one overload of getName() with a ref-qualifier (&&), the other one also should have the ref qualifier. This is why const& is required.

like image 75
P.W Avatar answered Nov 18 '22 01:11

P.W