0

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?

17
  • 2
    Are you referring to this? Commented Feb 21, 2013 at 22:42
  • 3
    Well it's const – is an immutable buffer useful to you? Commented Feb 21, 2013 at 22:43
  • It is not allowed in C++11. Commented Feb 21, 2013 at 22:43
  • 3
    @juanchopanza : Using std::string as a buffer is allowed in C++11, just by way of &str[0] rather than str.c_str(). Commented Feb 21, 2013 at 22:44
  • 3
    @RT_34, Undefined behaviour seems to work fine in many cases. In a couple of months, it then doesn't. Commented Feb 21, 2013 at 22:45

1 Answer 1

6

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;
  1. Returns: A pointer p such that p + i == &operator for each i in [0,size()].
  2. Complexity: constant time.
  3. 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().

Sign up to request clarification or add additional context in comments.

1 Comment

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.