简体   繁体   中英

Why should std::string's back() return a reference to a char?

The std::string's back() returns a reference to a char. Why a ref?

      char& back();
const char& back() const;

A reference allows you to alter the value referred to. This follows the behaviour of other containers in the Standard Library.

Then the question becomes: why not return a reference?

Because the back() function on standard containers gives you a reference to the last element, so that you can do things with that element.

std::string provides you with the same interface.

Why shouldn't it?

Ok, I see the point for the non-const version where you may want to modify that char. Is there any benefit to & on the const version?

<\/blockquote>

It might be efficient, and it might not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM