【问题标题】:Why do the const accessors of std::string return a reference?为什么 std::string 的 const 访问器返回引用?
【发布时间】:2015-08-29 12:04:51
【问题描述】:

std::string 访问器(backfrontatoperator[])具有const 和非const 重载,如下所示:

char& x();
const char& x() const;

为什么第二个版本返回 const 引用,而不是简单地返回 char 按值(作为副本)?

根据rules of thumb on how to pass objects around,不用修改原来的小对象不应该传值吗?

【问题讨论】:

  • 一个词:一致性(例如std::vector)。
  • 为什么它的语义应该与非常量版本不同?

标签: c++ c++11 stl language-design stdstring


【解决方案1】:

因为调用者可能想要一个对 char 的引用,这反映了通过非常量途径对其所做的任何更改。

std::string str = "hello";
char const& front_ref = static_cast<std::string const&>(str).front();
str[0] = 'x';
std::cout << front_ref; // prints x

【讨论】:

  • 更改为 const 对象?
  • @ixSci:不。您可以对非常量对象进行 const 引用。请参阅我更新的示例。
  • 当然可以,但是看起来是不是太做作了?我无法想象这样的情况。
  • @ixSci:仅仅因为您无法个人想象一个用例,并不意味着应该对界面进行任意限制。
  • @ixSci:不,是这样,因为没有理由任意限制它。
【解决方案2】:

因为上下文。

您正在处理名称暗示特定位置数据的容器和函数。

std::string s = "hello world?";
const auto& s1 = s.back();
s.back() = '!';

在这里返回引用提供了灵活性,它也与非常量变体和其他 stl 容器一致。毕竟这些函数其实都是std::basic_string&lt;char&gt;的成员。

请记住,“经验法则”是指导而不是规则。

【讨论】:

    猜你喜欢
    • 2012-11-10
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2021-12-31
    • 2021-07-10
    • 2018-07-22
    相关资源
    最近更新 更多