2 ms·
After a closer re-reading of C's rules on effective type, I think you're actually right, you return pointers-to-structs that point inside a (static or automatic
by Joker_vD 3y ago
After a closer re-reading of C's rules on effective type, I think you're actually right, you return pointers-to-structs that point inside a (static or automatic) char array, you have to slice the storage returned from malloc/calloc/realloc.
But C++ has std::launder that allows you to do that, see the very last example in [0]: it does placement-new on a char array, then launders the pointer to that array recasted as a pointer-to-struct, and it's supposed to not be UB.
[0] https://en.cppreference.com/w/cpp/utility/launder https://en.cppreference.com/w/cpp/utility/launder
- gpderetta 3y agoYou do not need launder for this. Placement new is enough as long as you refer to the newed object via the pointer returned by new. My understanding is that launder exists if you need to recover the pointer to the allocated object directly from the pool pointer. Re C, I'm far from expert, but I think that the issue exists primarily if you try to allocated within an existing named object (like in the parent examu). If you carve out your allocations from a larger chunk of anonymous memory it is supposedly conforming [A lot of "I think", "supposedly"... All object lifetimes and pointer derivation stuff is underspecified in the standards]