Can std::uintptr_t be used to avoid undefined behavior of out-of-bounds pointer arithmetic?

前端 未结 2 1673
無奈伤痛
無奈伤痛 2021-01-12 09:23

Now we know that doing out-of-bounds-pointer-arithmetic has undefined behavior as described in this SO question.

My question is: can we workaround such restriction b

2条回答
  •  灰色年华
    2021-01-12 10:19

    Yes, that is legal, but you must reinterpret_cast exactly the same uintptr_t value back to char*.

    (Therefore, what it you're intending to do is illegal; that is, converting a different value back to a pointer.)

    5.2.10 Reinterpret cast

    4 . A pointer can be explicitly converted to any integral type large enough to hold it. The mapping function is implementation-defined.

    5 . A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value;

    (Note that there'd be no way, in general, for the compiler to know that you subtracted one and then added it back.)

提交回复
热议问题