Is it legal to reuse memory from a fundamental type array for a different (yet still fundamental) type array

前端 未结 3 2052
甜味超标
甜味超标 2021-02-07 11:53

This is a follow up to this other question about memory re-use. As the original question was about a specific implementation, the answer was related to that specific implementat

3条回答
  •  日久生厌
    2021-02-07 12:10

    int *in = reinterpret_cast(buffer); // Defined behaviour because alignment is ok
    

    Correct. But probably not in the sense you'd expect. [expr.static.cast]

    A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.

    There is no int nor any pointer-interconvertible object at buffer, therefore the pointer value is unchanged. in is a pointer of type int* that points to a region of raw memory.

    for (int i=0; i

    Is incorrect. [intro.object]

    An object is created by a definition, by a new-expression, when implicitly changing the active member of a union, or when a temporary object is created.

    Noticeably absent is assignment. No int is created. In fact, by elimination, in is an invalid pointer, and dereferencing it is UB.

    The later float* all also follows as UB.

    Even in absence of all the aforementioned UB by proper use of new (pointer) Type{i}; to create objects, there is no array object in existence. The (unrelated) objects just happens to be side by side in memory. This means pointer arithmetic with the resulting pointer is also UB. [expr.add]

    When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the expression P points to element x[i] of an array object x with n elements, the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i+j] if 0 ≤ i+j ≤ n; otherwise, the behavior is undefined. Likewise, the expression P - J points to the (possibly-hypothetical) element x[i−j] if 0 ≤ i−j ≤ n; otherwise, the behavior is undefined.

    Where hypothetical element refers to the one past-the-end (hypothetical) element. Note that a pointer to a one past-the-end element that happens to be at the same address location as another object doesn't point to that other object.

提交回复
热议问题