Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

operators

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?

like image 485
amitizle Avatar asked Aug 02 '26 08:08

amitizle


2 Answers

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.

like image 196
Alexander Gessler Avatar answered Aug 04 '26 01:08

Alexander Gessler


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.

like image 44
Martin York Avatar answered Aug 04 '26 01:08

Martin York



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!