I am a little confused by why built-in types (like int
) are left uninitialized when default-initialized at automatic storage duration, while classes like std::string
are not.
I read the following StackOverflow post: Why do uninitialized objects of built-in type defined inside a function body have undefined value?, where it was explained that ints are left uninitialized at automatic storage duration to prevent overhead when functions are called multiple times. This is understandable, but why not do the same for strings and vectors then?
Is it because trying to deal with uninitialized vectors and strings could lead to much worse errors than trying to deal with uninitialized ints? That's the only explanation I could think of.
They (vectors and strings) would be very hard to use correctly if they could be uninitialized.
Let's say the vector is designed so that std::vector<int> v;
is uninitialized. If after that you do v = {1,2,3};
, the operator=
has to destroy the existing memory block, if any. How can it tell if there's an existing memory in the first place, if the pointer to it is uninitialized? You could now introduce a second kind of assignment (assign_to_uninitialized?) that ignores the existing contents, but this would be error-prone.
You could say that it's enough to zero the pointer but not size/capacity. This would work for the scenario above, but is still fairly error-prone.
What you can avoid initializing is std::string
's embedded character storage (used for SSO). Famously, libc++'s std::string
is faster to construct using std::string("")
rather than std::string()
, because the former doesn't zero the storage, other than setting the first byte to null.
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