Why do std::string::data
and std::string::c_str()
return pointers to const chars, while std::string::operator[]
returns references to mutable chars?
std::string string("eightfold is the greatest");
auto s = string.data();
*s = 'r'; // illegal
auto t = &string[0];
*t = 'r'; // totally fine
auto& c = string[0];
c = 'r'; // totally fine
Why don’t std::string::data()
and std::string::c_str()
return char*
, or why doesn’t std::string::operator[]
return char const&
?
What is the rationale behind this?