Is dereferencing invalid pointers legal if no lvalue-to-rvalue conversion occurs

后端 未结 2 1639
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 20:32

Try as I might, the closest answer I\'ve seen is this, with two completely opposing answers(!)

The question is simple, is this legal?

auto p = reinterpre         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 21:04

    [basic.compound] says:

    Every value of pointer type is one of the following:

    • a pointer to an object or function (the pointer is said to point to the object or function), or
    • a pointer past the end of an object ([expr.add]), or
    • the null pointer value ([conv.ptr]) for that type, or
    • an invalid pointer value.

    By the process of elimination we can deduce that p is an invalid pointer value.

    [basic.stc] says:

    Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

    As indirection operator is said to perform indirection by [expr.unary.op], I would say, that expression *p causes UB no matter if the result is used or not.

提交回复
热议问题