C++ const_cast usage instead of C-style casts

后端 未结 4 1530
长情又很酷
长情又很酷 2021-01-17 23:51

Why is the following?:

  const int i0 = 5;
//int       i1 = const_cast(i0);       // compilation error
  int       i2 = (int)i0;                           


        
4条回答
  •  礼貌的吻别
    2021-01-18 00:17

      const int i0 = 5;
    //int       i1 = const_cast(i0);       // compilation error
      int       i2 = (int)i0;                   // okay
    
      int       i3 = 5;
    //const int i4 = const_cast(i3); // compilation error
      const int i5 = (const int)i3;             // okay
    

    The compilation errors are caused because you don't cast const away/add const. Instead, you copy i0. For that operation, no cast is required at all:

    int i1 = i0;
    const int i4 = i3;
    

    The type you cast to should actually be a pointer or reference. Otherwise, using const_cast doesn't make sense since you could straight copy it. For pointers, for example, you can cast away the const, because dereferencing the pointer will yield another type for a const T* (yields const T) than for a T* (yields T). For references, the same is true: T& will access the object using another this pointer type than using const T&. Now what you really wanted to archive:

      const int i0 = 5;
    //int &     i1 = const_cast(i0);      // okay (but dangerous)
      int &     i2 = (int&)i0;                  // okay (but dangerous)
    
      int       i3 = 5;
    //const int&i4 = const_cast(i3); // ok now and valid!
      const int&i5 = (const int&)i3;             // okay too!
    

    The above can lead to undefined behavior, when you write to an originally const object through a reference to non-const (actually, merely casting and reading it isn't undefined behavior in itself. But if you're casting away const, you may also write to it, which then yields the undefined behavior)

提交回复
热议问题