Home>
class A {};
class B {};
A a;
B * b = reinterpret_cast<B *>(&a);

When you have code like above, variablesbIt seems obvious that if you do something about it, you will violate the strict alias rule. HoweverB * b = reinterpret_cast(&a);I don't know if it's already a violation at the stage of UB or if it's okay at this point. I think it's okay to think of it as a type problem when access actually occurs.

(Source of code:https://rinatz.github.io/cpp-book/ch08-01-cpp-casts/#reinterpret_cast)

c++
  • Answer # 1

    It can be read as a specification rule that limits "attempting to access a value". In other words, it should be interpreted that the behavior is not yet undefined at the time of casting the pointer.

  • Answer # 2

    I think it's okay to think of it as a type problem when access actually occurs.

    The so-called strict alias rule is a rule for "accessing a value via a different type of rvalue (glvalue)", so I think the interpretation in the question is okay. C ++ 17 [basic.lval]/8

    If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:
    -[...]

    Also, the conversion between pointers to different object types is well-defined itself. C ++ 17 [expr.reinterpret.cast]/p7

    An object pointer can be explicitly converted to an object pointer of a different type. When a prvaluevof object pointer type is converted to the object pointer type "pointer to cv"T", the result isstatic_cast(static_cast(v)). [...]

  • Answer # 3

    Hello.

    Strictly speaking, it should be a problem that should be dealt with in the standard, but if the assignment with the void pointer is "undefined behavior", a large part of the C language program will be undefined behavior. (Furthermorevoid *not only,int *Whenfloat *If even the substitution between is defined as undefined behavior, I think that there will be some undefined parts in the C language program. )
    Therefore, in principle, it is expected that the definition of "address is copied" is defined for the assignment between pointers.