Is it valid to cast and access to implicit-lifetime types without explicit object creation?

Viewed 85
char* t = (char*)malloc(sizeof(float) * 2);
*(float*)t = 1.0f; // or *reinterpret_cast<float*>(t) = 1.0f;
*((float*)t + 1) = 2.0f; // #1

In some SO questions, there are answers saying that above code is undefined behaviour because of strict-aliasing violation.

But, I read the paper P0593 recently.
I think the paper is saying If you allocate/obtain some storage using certain operations
(such as defining char/byte array, malloc, operator new, ...),
you can treat and use the storage itself as implicit-lifetime types without explicit object creation because the implicit types you want would be created implicitly.

  1. If my thought is correct, doesn't the above code now violate strict-aliasing rule?
  2. In the above code, Is a float array object created implicitly?
    (If not, #1 is UB because I tried pointer arithmetic on the storage which is not array)

(If you can't understand what i'm saying, tell me plz.. I'm not good at English..)

1 Answers

Yes, the code is legal, and the objects are created implicitly. (since C++20)

I had doubts whether you need std::launder or not. Seems not, malloc does it implicitly (note "return a pointer to a suitable created object").

Related