1

I have seen two methods to accomplish this in C++11:

std::string foo("Hello World");

// Option #1
const_cast<char*>(foo.c_str());

// Option #2
&foo[0]

Which one is the correct or most preferred method? Is there maybe an option #3 or more? My understanding is that std::string::data() does not guarantee null termination (which is important here), so I didn't list that as a valid option.

void.pointer
  • 24,859
  • 31
  • 132
  • 243
  • 1
    Does this answer your question? https://stackoverflow.com/a/16425373/241631 (the second paragraph is your use case) – Praetorian Feb 10 '15 at 19:25
  • Also worth the read, [see here](http://stackoverflow.com/a/14291203/1322972). – WhozCraig Feb 10 '15 at 19:27
  • @Praetorian Yes, that is a perfect answer. I was not able to find that despite my search before asking. Thank you. Should I delete my question since it's redundant? – void.pointer Feb 10 '15 at 19:31
  • @Praetorian Your linked answer suggests that it is ok to modify the underlying `char[]` after `const-cast`ing away the result of `c_str()`. `21.4.7.1[string.accessors]` of the standard says otherwise. – Pradhan Feb 10 '15 at 19:48
  • 1
    @Pradhan Seems the way I worded that is [open to misinterpretation](https://stackoverflow.com/questions/16425338/is-it-safe-to-pass-stdstring-to-c-style-apis/16425373#comment23555090_16425373). I've updated the answer, hopefully it's clear now. – Praetorian Feb 10 '15 at 19:54

0 Answers0