#include<iterator> std::ifstream testFile("testfile", std::ios::binary); // ... std::vector<char> fileContents; fileContents.reserve(fileSize); fileContents.assign(std::istreambuf_iterator<char>(testFile), std::istreambuf_iterator<char>());
All credits to wilhelmtell for the code. Whether or not this is more optimal though, is up for debate, as I think it has potential to be slightly slower (but not faster) than just a simple std::unique_ptr (I say it could potentially be slightly slower because it depends on exactly how the C++ implementation implements std::ifstream::read() and the above code... buffering (and copying into a temporary, intermediate buffer) can make a big difference, and I imagine that a single std::ifstream::read() may potentially just read directly into the buffer, while the std::istreambuf_iterator may potentially cause data to be read into an intermediate buffer before copying it over...). If you care that much, just try each one, look at the asm, and profile.
I might just go for a std::unique_ptr, for simplicity's sake.