Is this a good idea for reading into a std::vector
, or is there some gotcha here:
using namespace std;
ifstream file("blah.dat", ios::binary);
vector<T> v(N);
file.read(static_cast<char*>(v.data()), N * sizeof(T));
Does the vector
standard allow me to do this to populate a vector? For simplicities sake, let us assume that T is a Plain Old Data Type.
There's no undefined behavior here if T
is trivially copyable, which PODs certainly are. vector<T>::data
is guaranteed to return a pointer to a contiguous array of vector<T>::size
T
s, and the object representation of a trivially copyable type T
is guaranteed to be a contiguous sequence of sizeof(T)
bytes (possibly including internal padding).
If the bytes you store into that space aren't valid T
object representations, you could get undefined behavior when you access them. Exactly which byte sequences constitute a valid T
object representation is a bit of a grey area; at the very least you should be able to portably write the underlying bytes of an object of a trivially copyable type to file and successfully read them back into the underlying bytes of an object of the same type.
For paranoia's sake, I'd probably put:
static_assert(std::is_trivially_copyable<T>(),
"NO NO NO - T MUST BE TRIVIALLY COPYABLE!");
before the file.read
for future-proofing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With