是否允许在不同类型的const之间进行static_cast ?

Is it allowed to static_cast between different types of const?

本文关键字:static cast 之间 const 同类型 是否      更新时间:2023-10-16

到目前为止,我很少看到顶层const之间的static_cast。
最近,我不得不使用static_cast来显示指向const对象的指针的地址,我得出了这个问题:
是否允许在不同类型的const之间进行static_cast ?

它通过了gcc 4.7的编译。但我只是想确认一下,不是UB。谢谢。

  const int a = 42; // test case 1, const obj
  const double b = static_cast<const double>(a);
  cout << b << endl;

  const int c = 0; // test case 2, pointer to const obj
  cout << static_cast<const void*>(&c) << endl;

From [expr.static.cast]

[…static_cast操作符不能抛弃constness

static_cast添加 const是完全可以的,然后你不需要在你的测试用例

const int a = 42; // test case 1, const obj
const double b = static_cast<double>(a); // Works just as well.
const double b = a; // Of course this is fine too

我想您想要将conststatic_cast一起添加的少数几次之一是显式调用重载函数

void foo(int*) { }
void foo(int const*) { }
int main()
{
  int a = 42;
  foo(&a);
  foo(static_cast<int const*>(&a));
}