到目前为止,我很少看到顶级 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]
[...] The static_cast operator shall not cast away 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));
}
尽管使用正确设计的代码,您实际上并不需要这样做。
关于c++ - 是否允许在不同类型的 const 之间进行 static_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24770653/