Reading n chars from stream to string I need to read n chars from a binary file into a string. Currently, what I do is:

static string Read(istream &amp;stream, uint32_t count)
{
    auto bytes = unique_ptr&lt;char[]&gt;(new char[count]);

    stream.read(bytes.get(), count);

    return string(bytes.get(), count);
}


I found the way I deal with the array of chars quite messy. If I used new and delete[] directly, it would make the code messy in another way (I would need to add a local variable for the result). And I'm trying to avoid delete as a general rule.

Is there a clear way to write this code? The fact that it uses twice as much memory as it needs is probably not a big deal, but fixing that would be nice too.
Why not:

static string Read(istream &amp;stream, uint32_t count)
{
    std::string result(count, ' ');
    stream.read(&amp;result[0], count);

    return result;
}


Though not strictly C++03 compatible that is easily validated. One of the reasons the committee found it easy to add the new constraint in C++11 was that no implementation did not use contiguous memory (Random Access Iterators are a hint).

But a C++03 strict implementation would be:

static string Read(istream &amp;stream, uint32_t count)
{
    std::vector&lt;char&gt; result(count);  // Because vector is guranteed to be contiguous in C++03
    stream.read(&amp;result[0], count);

    return std::string(&amp;result[0], &amp;result[count]);
}