的前提条件之一是std::launder
要求对象在其生命周期内。我认为这是能够取消引用元素的必要条件。这是否意味着,如果我获得指向数组元素的指针,那么如果我只执行算术,则不需要洗钱?还是只是UB?
一个清晰的代码示例。在代码的注释中做了一些澄清问题的评论。
alignas(T) std::byte memory[3 * sizeof(T)]; // implicitly creates an array of 3 T
// elements on the stack
auto arr_ptr = std::launder(reinterpret_cast<T(*)[3]>(memory));
// Now we have an implictly created array of 3 T, but unless T is an
// implicit-lifetime type, no element has began its lifetime yet
auto ptr1 = reinterpet_cast<T*>(memory); // points to the storage occupied by the
// first element of T
// is arithmetic on ptr1 valid? Or it is treated as regular conversion between
// types that are not pointer interconvertible, and since no T element exists
// there, arithmetic is UB by the standard.
// Or, since the address is of an valid element of array of T
// (storage address is the same, and we do not // dereference it), everything is
// okay?
auto ptr2 = std::launder(reinterpret_cast<T*>(memory));
// does not point to an object within its lifetime, UB, therefore, it can not be
// used for pointer arithmetic.