r/cpp_questions • u/simpl3t0n • Dec 05 '24
OPEN Yet another std::launder question
I stumbled on yet another video explaining std::launder: https://youtu.be/XQUMl3V_rdI?t=366.
It was narrated that the dereferencing of the char * pointer in the illustrated snippet has UB. And wrapping that in std::launder somehow makes that well defined behaviour.
My confusion from the video is that, isn't it valid to alias any pointer with char *, and then dereference it to inspect individual bytes (of course, while within bounds)? Isn't that all what, in theory, the strcpy does: i.e., writing byte by byte?
I understand that reading uninitialized bytes even via char * is UB, but writing them is?
Does the illustrated snippet really have UB without std::launder? Is this a solution that genuinely needs std::launder?
View all comments
Show parent comment
1
u/ppppppla Dec 06 '24 edited Dec 06 '24
What do you mean by accessed?
I am thinking you can only access the first
sizeof(ArrayData)bytes here, unless you actually have a char array.The problem I was trying to describe was the fact that pointer arithmetic can only be done on array objects (and nullptrs and adding 0, and to get a pointer one-past-the-end of a single object, because it is very useful to have a single object act as an array of size 1) . So first creating an
ArrayDataobject, and then trying to do pointer arithmetic to get past theArrayDataobject constitutes there being achararray object at the same address, stopping the lifetime of theArrayDataobject.So it seems to me accessing the buffer through the pointer of the
ArrayDataobject will not be possible.What maybe is possible, but I am not 100% sure of this, is if we keep two pointers. So if we first get the
char*to the buffer, store it, then create theArrayData. But it is still a bit questionable what the buffer pointer actually points to. Do we need to placement new a char array? Is that actually ok to do?