C++: Safe reading from file with std::string (&str[0]) as a buffer?

173 views Asked by At

I have a binary file that I'm reading from. In the file at one point, there is a known number of bytes which make up a simple ASCII string (possibly with newlines). Right now I have:

void doSomething(istream &in) {
    vector<char> buf(length + 1, '\0');
    in.read(&buf[0], length);
    string str(&buf[0]);
}

But I realized that it would probably be faster to do

void doSomething(istream &in) {
    string str(length + 1, '\0'); // +1 needed?
    in.read(&str[0], length);
}

I tried looking in the standard to see if string allocation is always sequential or if it's safe doing something like this. Safe meaning, no accidental reading into (writing to) memory not part of the string. Does anyone know?

1

There are 1 answers

4
bames53 On BEST ANSWER

std::string allocation is always sequential, at least as of C++11. I believe prior to that it wasn't clearly defined so, but no implementations used non-sequential storage.

You do not need to explicitly add space for a null terminator in std::string.