Quote Originally Posted by laserlight
Since you are compiling using a known set of compilers, you could just check if the given standard library implementations store the contents of std::string contiguously. If one of them doesn't, or if you cannot determine this, then I would not recommend using &s[0] as it is better to be safe than sorry.
Well, unless we were using a compiler that supports C++11, I am reluctant to use that construct regardless. And yes, I agree it's better to be safe than sorry. That's why I moved the contents into a vector in the first place.
Quote Originally Posted by laserlight
If this is due to a legacy interface that is not const-correct, and it is documented that the contents of the array is not modified through that pointer to non-const char, then using data() and casting away const-ness is fine.
It is not documented anywhere in the library that the contents are or are not modified. And again, it's better to be safe than sorry. One question though, is data() guarenteed to return a null terminated string, or is that also implementation dependent? If not, this could also potentially cause a core dump by the library call.
Quote Originally Posted by D_Drmmr
If the memory pointed to by the (const-casted) pointer is not modified by the function, all is fine.
Yes, but we don't know that. And all would be fine only if data() returned a null terminated string.
Quote Originally Posted by Paul McKenzie
What's the signature of the called function? If it is not const char*, then why isn't it const char*?
Actually I mentioned that the signature of the COTS library requires a non-const pointer to char. What I should have said is a pointer to a non-const char, or more appropriately, a non-const pointer to a non-const char (i.e. char*), sorry. Anyway, I have no idea why the library calls were written that way. It is an extremely old COTS product that we are simply having to deal with. Oh, and thanks for the Scott Meyers quote!
Quote Originally Posted by Philip Nicoletti
From the 2003 standard:
Thanks for the quote.
==========================================================
So, after all of this, I have a few more questions.
Does anyone have a quote from the standard that indicates std::string is implementation dependent and is not guaranteed to be in contiguous memory (prior to the C++11 standard of course)?
Does data() return a char const* to memory that is independent of the memory where the actual string is stored, or is this also implementation dependent?
Is the location of the data that data() returns guaranteed to be null terminated?
The answers to these would indicate to me whether or not it’s safe to cast the const-ness away from the return from data(), regardless of whether or not the function is modifying the contents. But I usually steer away from dangerous (IMHO) stuff like this anyway and simply try to play it safe. That’s why I used a vector. My co-worker is very persistent though, so I just needed some proof.