My copy of a draft C++ standard (labelled "ISO/IEC JTC1 SC22 WG21 N3690
Date: 2013-05-15") has the following definition for basic_string::c_str() and basic_string::data().
const charT* c_str() const noexcept; const charT* data() const noexcept;Returns: A pointer
psuch thatp + i == &operator[](i)for eachiin[0,size()].Complexity: constant time.
Requires: The program shall not alter any of the values stored in the character array.
It appears, then, that the following C++ program has undefined behaviour, as it trips over the requirement from c_str():
#include <string>
int main() {
std::string foo = "foo";
foo.c_str();
foo[2] = 'p';
}
This seems breathtakingly stupid. Have I misread the standard, or is this requirement on c_str a relic from a bygone era?