的std::string
存取器(back
,front
,at
,和operator[]
)具有const
和非const
过载,如下:
char& x();
const char& x() const;
为什么第二个版本会返回const
引用,而不是简单地char
按值(作为副本)返回?
根据有关如何传递对象的经验法则,当不需要修改原始对象时,是否应该按值传递小对象?
因为调用者可能想要引用char,所以它反映了通过非const途径对其所做的任何更改。
std::string str = "hello";
char const& front_ref = static_cast<std::string const&>(str).front();
str[0] = 'x';
std::cout << front_ref; // prints x
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句