While this may well be a stupid question, I saw something about how you shouldn't do this, despite the fact that it is allowed in C++ 11, but I don't quite get why. Could anyone explain why this is?
1 Answer
It's not allowed!
21.4.7 basic_string string operations[string.ops]
21.4.7.1 basic_string accessors[string.accessors]
const charT* c_str() const noexcept; const charT* data() const noexcept;
- Returns: A pointer p such that p + i == &operator for each i in [0,size()].
- Complexity: constant time.
- Requires: The program shall not alter any of the values stored in the character array.
Other than that, you're modifying data references by a const char *, which usually indicates a const_cast<char*>. Not only will this result in undefined behaviour, but according to Herb Sutter const should be read as thread-safe nowadays (see his talk about const and mutable).
However, as it has been stated, the use of std::string str; &str[0] is safe if str is sufficiently large. Just don't use .c_str() or .data().
1 Comment
David Rodríguez - dribeas
The
const_cast will cause undefined behavior only when a) casting away const-ness of an object that is const (rather than a reference that is const) and b) it is used to modify the object. The second part would be true, the first one depends on whether the string on which c_str() is called is const or not (and even if it is const, it might be that the buffer is still not const...). That being said, the better approach is using &str[0]
const– is an immutable buffer useful to you?std::stringas a buffer is allowed in C++11, just by way of&str[0]rather thanstr.c_str().