const qualifiers are used to indicate that a function or method will not modify the object it is called on. When used with getters, const ensures that the getter function does not modify the object's state. On the other hand, const& qualifiers are used to indicate that a reference to a constant object is being returned. This means that the getter function returns a reference to a constant object, which cannot be modified. So, the main difference between getters with const and with const& qualifiers lies in whether the returned object is constant or not.

12
我看过 Nicolai Josuttis(C++ 标准委员会成员)的一个talk(确切的时间戳,他没有解释),他说自从 C++11 以来,getter 应该这样写:
const std::string& getName() const&
{
     return memberStringVar;
} 

问题是,与这个getter相比有什么区别?
const std::string& getName() const
{
     return memberStringVar;
}

2
对于第一个,C{}.getName()是非法的。 - Passer By
1
@PasserBy,使用您的示例,第一个可以通过clang编译。 - Croolman
显然我误解了ref-qualifier,我不知道事情为什么会变成这样。 - Passer By
2
在这个讲话中,有一个 && getter(用于 rvalues)。如果存在这个 getter,另一个 getter 必须具有 ref-qualifier,因此你的第二个示例无法工作。 - geza
2
可能是什么是“rvalue reference for *this”?的重复问题。 - user4290866
显示剩余3条评论
1个回答

9
在演讲中给出的示例中,getName()有两个重载版本,一个带有&&,另一个带有const&限定符。
如果const std::string& getName() const没有&,则无法与rvalue的重载string Customer::getName() &&一起使用。
如果要使其正常工作,则必须完全删除rvalue重载。
由于ref qualified成员函数仅在C++11中添加(从而使得rvalues的getter成为可能),所以需要从const std::string& getName() const更改为const std::string& getName() const&以使两个重载都能正常工作。
C++17标准草案n4659声明:

16.1 可重载声明 [over.load]
...

2 某些函数声明无法进行重载:
...
(2.3) — 如果存在具有相同名称和相同参数类型列表的成员函数声明以及具有相同名称、相同参数类型列表和相同模板参数列表的成员函数模板声明,但它们中的任何一个(而不是全部)都具有引用限定符,则不能对其进行重载

由于 getName() 存在一个带有引用限定符 (&&) 的重载,因此另一个也应该具有引用限定符。这就是为什么需要 const& 的原因。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接