C++ const_cast 使用而不是 C 风格的强制转换

2023-11-24

为什么会出现以下情况?:

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

  int       i3 = 5;
//const int i4 = const_cast<const int>(i3); // compilation error
  const int i5 = (const int)i3;             // okay

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

  int       i3 = 5;
//const int i4 = const_cast<const int>(i3); // compilation error
  const int i5 = (const int)i3;             // okay

编译错误是因为您没有将 const 丢弃/添加 const 而引起的。相反,您复制 i0。对于该操作,根本不需要强制转换:

int i1 = i0;
const int i4 = i3;

您转换为的类型实际上应该是指针或引用。否则,使用 const_cast 没有意义,因为您可以直接复制它。例如,对于指针,您可以放弃 const,因为取消引用指针将产生另一种类型const T*(产量const T)比对于一个T*(产量T)。供参考,同样如此:T&将使用另一个对象访问该对象this指针类型比使用const T&。现在您真正想要存档的是:

  const int i0 = 5;
//int &     i1 = const_cast<int&>(i0);      // okay (but dangerous)
  int &     i2 = (int&)i0;                  // okay (but dangerous)

  int       i3 = 5;
//const int&i4 = const_cast<const int&>(i3); // ok now and valid!
  const int&i5 = (const int&)i3;             // okay too!

当您通过对非 const 的引用写入最初的 const 对象时,上述情况可能会导致未定义的行为(实际上,仅仅转换和读取它本身并不是未定义的行为。但是如果您要放弃 const,您可能会也写入它,然后产生未定义的行为)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ const_cast 使用而不是 C 风格的强制转换 的相关文章

随机推荐