2

The std::string accessors (back, front, at, and operator[]) have const and non-const overloads, as below:

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

Why does the second version return a const reference, as opposed to simply returning the char by value (as a copy)?

According to the rules of thumb on how to pass objects around, shouldn't small objects be passed by value when there's no need to modify the original?

2
  • 2
    One word: consistency (with std::vector for instance). Commented Jun 13, 2015 at 16:02
  • Why should it have different semantics than the non-const version? Commented Jun 13, 2015 at 16:27

2 Answers 2

10

Because the caller might want a reference to the char, that reflects any changes made to it through non-const avenues.

std::string str = "hello";
char const& front_ref = static_cast<std::string const&>(str).front();
str[0] = 'x';
std::cout << front_ref; // prints x
Sign up to request clarification or add additional context in comments.

9 Comments

changes to const object?
@ixSci: No. You can have a const reference to a non-const object. See my updated example.
Sure, but doesn't it look too much contrived? I can't imagine such a case whatsoever.
@ixSci: Just because you can't personally imagine a use case, doesn't mean the interface should be arbitrarily restricted.
@ixSci: No, it's that way because there's no reason to arbitrarily restrict it.
|
1

Because context.

You're dealing with a container and functions with names that imply specific positional data.

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

Returning a reference here provides flexibility, it's also consistent with the non-const variants and other stl containers. After all these functions are actually members of std::basic_string<char>.

Remember that "rule of thumb" is a guideline not a rule.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.