Quantcast
Channel: User HolyBlackCat - Stack Overflow
Viewing all articles
Browse latest Browse all 1285

Answer by HolyBlackCat for Why are some types left uninitialized when default initialized while others are not?

$
0
0

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.


Viewing all articles
Browse latest Browse all 1285

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>