【发布时间】:2013-11-14 10:49:34
【问题描述】:
为什么std::string::data 和std::string::c_str() 返回指向const 字符的指针,而std::string::operator[] 返回指向可变 字符的引用?
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
为什么std::string::data()和std::string::c_str()不返回char*,或者std::string::operator[]为什么不返回char const&?
这背后的原理是什么?
【问题讨论】:
-
请注意
&s[0]返回的char*不能被视为以null结尾的字符串,而c_str()返回的char const*是以null结尾的字符串。 -
@Nawaz,我几乎可以肯定 null 保证在 C++11 中存在(并且它是连续的),即使您无法修改它。
-
@Nawaz:在 C++11 中,
&s[0]保证是 C 字符串。在 C++11 之前的语言版本中,不能保证。 -
@AndreyT:是的,我记得。谢谢提醒。
标签: c++ string constants design-rationale design-choices