0

I am reading about STL string class. It is mentioned as below

STL string class chooses not to define conversion operators, but rather use the c_str() and data() methods for directly accessing the memory. The STL purposely does not include implicit conversion operators to prevent misuse of raw string pointers.

My question is

  1. c_str() returns const char* pointer and still user can modify string value. Am I right?
  2. What does the author mean by "to prevent misuse of raw string pointers"? Please explain, preferably with an example.

Thanks!

7
  • 2
    1. what do you think the const means? Commented Jul 22, 2013 at 14:15
  • 1
    1. You can modify the string, but not via the pointer returned by c_str() or data(). 2. Modifying the contents of the underlying string data without maintaining invariants. For example, by modifying via the pointer returned by c_str() or data(). Commented Jul 22, 2013 at 14:16
  • ... c2.com/cgi/wiki?StlIsNotTheCppStandardLibrary Commented Jul 22, 2013 at 14:17
  • @StoryTeller Even standard library implementation maintainers refer to it as STL. The term simply changed its meaning over time. Commented Jul 22, 2013 at 14:26
  • @KonradRudolph, well, they are wrong :P Commented Jul 22, 2013 at 14:52

1 Answer 1

2

No, you cannot use the return value of std::string::c_str() to modify the string. Trying to do so is undefined behavior. And the problem was (and still is) the lifetime of the pointer returned by std::string::c_str(). It becomes invalid if the string is destructed, or if any non-const function is called on the string. The issues are things like:

char const* s = string1 + string2;
//  s is invalid here.

vs.

char const* s = (string1 + string2).c_str();
//  s is invalid here.

In the first case, it's easy to make the mistake, without realizing it, so the committee decided to not have implicit conversion, so that this would be illegal. In the second case, you have to really want to.

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

Comments

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.