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

发布于 2024-12-06 10:57:24 字数 170 浏览 0 评论 0原文

谁能解释一下

const char& operator[] const

char& operator[]

C++ 中的 之间的区别吗? 第二个确实是重复字符串吗?为什么?

Can anyone please explain the difference between:

const char& operator[] const

and

char& operator[]

in C++?
Is it true that the second one is duplicating the string? and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

安静 2024-12-13 10:57:24

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

std::string s = "Hell";
s[0] = 'B';

// s is "Bell" now

鉴于此示例,char&当然,operator[] 可用于访问单个字符而不修改它,例如在 std::cout<< 中。 s[0];

但是,需要 const 重载,因为您无法在 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 方法。

No, the second returns a non-constant reference to a single character in a string, so you can actually use it to alter the string itself (the string object is not duplicated at all, but its contents are possibly modified).

std::string s = "Hell";
s[0] = 'B';

// s is "Bell" now

Given this sample, char& operator[] can of course be used to access a single character without modifying it, such as in std::cout<< s[0];.

However, the const overload is needed because you cannot call non-const member functions on const objects. Take this:

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';

Generally, the compiler will pick the const overload only when being called on a const object, otherwise it will always prefer to use the non-const method.

太阳哥哥 2024-12-13 10:57:24

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

第一个方法被定义为 const 方法(最后一个 const),因此承诺不更改任何成员。为了确保您不能通过返回的引用更改内部成员,这也是 const。

  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

第二个确实是重复字符串吗?为什么?

不,因为事实并非如此。

They both return references to the internal member of the string.

The first method is defined as a const method (the last const) and as such promises not to change any members. To make sure you can;t change the internal member via the returned reference this is also const.

  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.

This allows you to read members from the string:

std::string const  st("Plop is here");

char x  = st[2];          // Valid to read gets 'o'
st[1]   = 'o';            // Will fail to compile.

For the second version it say we return a reference to an internal member. Neither promise that the object will not be altered. So you can alter the string via the reference.

   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

Is it true that the second one is duplicating the string? and why?

No. Because it does not.

花开雨落又逢春i 2024-12-13 10:57:24

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

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

The issue is with const-correctness. Allowing read-only access in a const string and allowing writable access in a mutable string require two methods.

The const char& operator[] const accessor is necessary if you want to access a character from a const std::string. The char& operator[] accessor is necessary to modify a character in a std::string.

情愿 2024-12-13 10:57:24

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

现在,如果您有写时复制字符串(有时采用的优化),那么获取对字符串片段的非常量引用可能意味着复制(因为引用意味着写入)。这可能会或可能不会发生在您的特定平台(您未指定)上。

The second one does not need to duplicate (copy) the string. It just returns a reference to a character which is modifiable. The first one returns a non-modifiable reference, because it has to: the function itself is const, meaning it can't mutate the state of the string.

Now, if you have copy-on-write strings (an optimization employed sometimes), then getting a non-const reference to a piece of the string may imply copying (because the reference implies writing). This may or may not be happening on your particular platform (which you didn't specify).

就像说晚安 2024-12-13 10:57:24

一些基础知识:

With operator[] you can both edit value in a container/memory and read value.

With const char& operator[] const you are only allowed to read value.
Eg.

<代码>

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


char& operator[] 您可以编辑该值。例如
<代码>

ss[1] = 'A';


Some Basics :

With operator[] you can both edit value in a container/memory and read value.

With const char& operator[] const you are only allowed to read value.
Eg.

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

with char& operator[] you can edit the value. Eg

ss[1] = 'A';

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文