以 const 和 const 结尾的 getter 之间的区别
Difference between getters ending with const and const&
我看过 Nicolai Josuttis(C++ 标准委员会成员)的 talk(确切的时间戳,他没有解释),他说 getter 应该这样写:
const std::string& getName() const&
{
return memberStringVar;
}
从 C++11 开始。问题是,和这个getter有什么区别?
const std::string& getName() const
{
return memberStringVar;
}
在演讲中给出的示例中,给出了 getName()
的两个重载。
一个带有 &&
,另一个带有 const&
限定符。
在 const
之后没有 &
,函数 const std::string& getName() const
不能用右值 string Customer::getName() &&
的重载来重载。
如果您想让它工作,则必须从代码中完全删除右值重载。
由于仅在 C++11 中添加了 ref 限定成员函数(使右值的 getter 成为可能),因此需要从 const std::string& getName() const
更改为 const std::string& getName() const&
才能使两者可能过载。
C++17 标准草案 n4659 指出:
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.
因为有一个 getName()
的重载带有 ref 限定符 (&&
),所以另一个也应该有 ref 限定符。这就是为什么需要 const&
。
我看过 Nicolai Josuttis(C++ 标准委员会成员)的 talk(确切的时间戳,他没有解释),他说 getter 应该这样写:
const std::string& getName() const&
{
return memberStringVar;
}
从 C++11 开始。问题是,和这个getter有什么区别?
const std::string& getName() const
{
return memberStringVar;
}
在演讲中给出的示例中,给出了 getName()
的两个重载。
一个带有 &&
,另一个带有 const&
限定符。
在 const
之后没有 &
,函数 const std::string& getName() const
不能用右值 string Customer::getName() &&
的重载来重载。
如果您想让它工作,则必须从代码中完全删除右值重载。
由于仅在 C++11 中添加了 ref 限定成员函数(使右值的 getter 成为可能),因此需要从 const std::string& getName() const
更改为 const std::string& getName() const&
才能使两者可能过载。
C++17 标准草案 n4659 指出:
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.
因为有一个 getName()
的重载带有 ref 限定符 (&&
),所以另一个也应该有 ref 限定符。这就是为什么需要 const&
。