I'm trying to fully understand a C++20 new feature, Implicit creation of objects.
There is this example in the proposal, section "3.3 Type punning":
We do not wish examples such as the following to become valid:
float do_bad_things(int n) { alignof(int) alignof(float) char buffer[max(sizeof(int), sizeof(float))]; *(int*)buffer = n; // #1 new (buffer) std::byte[sizeof(buffer)]; // #X return (*float*)buffer; // #2 }
The proposed rule would permit an int object to spring into existence to make line #1 valid (in each case), and would permit a float object to likewise spring into existence to make line #2 valid.
Why is the line marked #X (by me) necessary? Does it make a difference? Wouldn't the example be exactly the same, if this line weren't there?
My reasoning is: buffer
is a char array, so it implicitly creates objects. So, at line #1, an int
is implicitly created. Likewise, at line #2, a float
gets implicitly created, even without line #X (because buffer
already has the implicitly-creates-objects property). So it seems that line #X doesn't add anything. Am I wrong?