On page 18 of Bjarne Stroustrup's "A Tour of C++" (second edition), he states "for almost all types, the effect of reading from or writing to an uninitialized variable is undefined".
I understand why reading from an uninitialized variable is undefined behaviour, but why is writing to an uninitialized variable undefined behaviour? Surely I am missing something, because otherwise doing something like int x;
is completely useless because you cannot read from or write to x
(i.e. cannot do anything with x
) without triggering undefined behaviour (assuming int
is one of the "almost all types" that this applies to).
Writing to an uninitialized variable is fine. The only time you get undefined behavior with uninitialized variables is when you try and read from them before anything is written to them. Then you have undefined behavior because that value it has is undefined.
Now what is undefined behavior is writing to an object whose lifetime has not begun. For example if you have a struct like
struct foo
{
std::string str;
};
and you acquire memory for it with malloc
like
foo* f = malloc(sizeof(foo));
then you can't do
f->str = "some text";
The reason for this is because malloc
does't actually give you an object. All it does is allocate storage for the object, which is not enough to consider that you actually have an object since std::string
has a non trivial constructor meaning foo
's constructor is non trivial as well. In order for the lifetime of *f
to start you need to call foo
's constructor. To do that you use placement new which will construct the object in the memory you provide to it. That would look like
foo* f = malloc(sizeof(foo));
new(f) foo;
This is most likely what Bjarne is trying to talk about.
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