cplusplus / CWG

Core Working Group
23 stars 7 forks source link

CWG2861 [expr.dynamic.cast] The behaivor is underspecified when `v` does not point to that object #497

Open xmh0511 opened 5 months ago

xmh0511 commented 5 months ago

Full name of submitter (unless configured in github; will be published with the issue): Jim X

Consider this example:

struct A{
    virtual void foo(){}
};
struct B{
    virtual void foo2(){}
};
struct D:A,B{
   virtual void foo(){

   }
};
struct No{};
int main(){
  No no;
  B* ptr = (B*)&no;
  try{
    auto r = dynamic_cast<D*>(ptr);
    std::cout<< (long long int)r;
  }catch(...){

  };
}

This example just causes the segment fault in major implementations. However, [expr.dynamic.cast] does not specify the behavior for this case.

Suggested Resolution

Append a wording before [expr.dynamic.cast] p7

If the type of the object pointed or referred to by v is not similar to the pointed or referred type by v, the behavior is undefined.

jensmaurer commented 4 months ago

CWG2861

t3nsor commented 4 months ago

We currently define "dynamic type" only for expressions, not objects. Maybe we can say

Otherwise, if v has type "pointer to cv U" and v does not point to an object whose type is similar to U, the behavior is undefined. If v is a glvalue of type "cv U" and v does not refer to an object whose type is similar to U, the behavior is undefined.

This also addresses the case of "what object?" when v is a past-the-end pointer.

jensmaurer commented 4 months ago

Agreed, fixed.