std::string 的运算符 [] 和常量运算符 [] 之间的区别

Difference between std::string's operator[] and const operator[]

本文关键字:运算符 之间 区别 常量 std string      更新时间:2023-10-16

有人能解释一下之间的区别吗

const char& operator[] const

char& operator[]

在C++中?第二个是真的在复制字符串吗?为什么?

否,第二个返回对字符串中单个字符的非常量引用,因此您实际上可以使用它来更改字符串本身(字符串对象根本不重复,但其内容可能会被修改(。

std::string s = "Hell";
s[0] = 'B';
// s is "Bell" now

给定此示例,char& operator[]当然可以用于访问单个字符,而无需对其进行修改,例如在std::cout<< s[0];中。

但是,const重载是必需的,因为您不能在常量对象上调用非常量成员函数。拿这个:

const std::string s = "Hell";
// ok, s is const, we cannot change it - but we still expect it to be accessible
std::cout << s[0];
// this, however, won't work, cannot modify a const char&
// s[0] = 'B';

通常,编译器只有在对常量对象调用时才会选择const重载,否则它总是倾向于使用非常量方法。

它们都返回对字符串内部成员的引用。

第一个方法被定义为const方法(最后一个const(,因此承诺不更改任何成员。确保你可以;t通过返回的引用更改内部成员这也是常量。

  const char& operator[](int i) const
//                              ^^^^^ this means the method will not change the state
//                                    of the string.
//^^^^^^^^^^^  This means the object returned refers to an internal member of
//             the object. To make sure you can't change the state of the string
//             it is a constant reference.

这允许您从字符串中读取成员:

std::string const  st("Plop is here");
char x  = st[2];          // Valid to read gets 'o'
st[1]   = 'o';            // Will fail to compile.

对于第二个版本,它说我们返回对内部成员的引用。两者都不承诺该对象不会被更改。因此,您可以通过引用更改字符串。

   char& operator[](int i)
// ^^^^^  Returns a reference to an internal member.
std::string mu("Hi there Pan");
char y = mu[1];           // Valid to read gets 'i'
mu[9]  ='M';              // Valid to modify the object.
std::cout << mu << "n";  // Prints Hi there Man

第二个是真的在复制字符串吗?为什么?

没有。因为事实并非如此。

问题在于常量正确性。允许在常量字符串中进行只读访问和允许在可变字符串中进行可写访问需要两种方法。

如果要从const std::string访问字符,则const char& operator[] const访问器是必需的。char& operator[]访问器是修改std::string中的字符所必需的。

第二个不需要复制字符串。它只是返回一个对可修改字符的引用。第一个返回一个不可修改的引用,因为它必须:函数本身是const,这意味着它不能改变字符串的状态。

现在,如果您有写时复制字符串(有时会使用优化(,那么获得对字符串片段的非常量引用可能意味着复制(因为引用意味着写入(。这可能发生在您的特定平台上,也可能不会发生(您没有具体说明(。

一些基础知识:

使用运算符[],您既可以编辑容器/内存中的值,也可以读取值。
使用const char& operator[] const时,您只能读取值。例如。

std::string ss("text");
char a = ss[1];

使用char& operator[]可以编辑该值。例如

ss[1] = 'A';