繁体   English   中英

是否可以在不同类型的const之间进行static_cast?

[英]Is it allowed to static_cast between different types of const?

到目前为止,我很少见过顶级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;

来自[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

我想您想用static_cast添加const的少数情况之一是显式调用重载函数

void foo(int*) { }
void foo(int const*) { }

int main()
{
  int a = 42;

  foo(&a);
  foo(static_cast<int const*>(&a));
}

尽管使用正确设计的代码,您实际上并不需要这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM