c++ - Why do the const accessors of std::string return a reference? -


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

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

why second version return const reference, opposed returning char by value (as copy)?

according rules of thumb on how pass objects around, shouldn't small objects passed value when there's no need modify original?

because caller might want reference char, reflects changes made 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 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -