[LC++]geting a "char *" (not const) from a string.data()
Chris Vine
chris at cvine.freeserve.co.uk
Tue Jul 31 11:37:03 UTC 2001
On Monday 30 July 2001 12:38, Jan Pfeifer wrote:
> actually i have a parsing function that receives a string (text). So i
> want to read a whole text file into a string and pass it to the function.
> But i wanted to do this without having to read the file into a char
> buffer, and then copy to the string. I was wondering if there were, as you
> said a way to do a "string::resize" and get a pointer to this data, so
> that i could read the file directly there.
>
> any idea ?
>
>
> thanks for the answer,
>
> jan
[snip]
As with the case of std::vector<char>, you could do -
std::string text;
text.resize(filesize);
read(fd, &text[0], filesize);
The non-const version of std::string::operator[]() returns a reference to the
stored character -- it is intended to be available as a modifying access so
that an expression like text[0] = 'a'; is a legitimate expression.
Accordingly, using that operator to access the entire stored character
sequence of the string will probably work with most or all implementations of
std::string. std::string::data() and std::string::c_str() return an internal
array or C string respectively of type const char*, which implies, but does
not require, that a reasonable implementation of std::string (a synonym for
std::basic_string<char>) will store characters in contiguous memory.
However, I don't think that is actually a guarantee. Amongst other matters,
modifying the output of std::string::data() or std::string::c_str() results
in undefined behaviour. I think the defect report concerning contiguity only
applies to std::vector.
If you use this form, technically therefore I think it will be non-standard
(but will probably work on all practical implementations). Others on the
list may be able to confirm whether the defect report applies to
std::basic_string<char>.
Chris.
More information about the tuxCPProgramming
mailing list