是否允许在不同类型的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;
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
我想您想要将const
与static_cast
一起添加的少数几次之一是显式调用重载函数
void foo(int*) { }
void foo(int const*) { }
int main()
{
int a = 42;
foo(&a);
foo(static_cast<int const*>(&a));
}
相关文章:
- 如何理解C++标准N3337中的expr.const.cast子句8
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- C++Cast运算符过载
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 收到错误"invalid use of non-static data member 'stu::n' "
- LNK1104:无法打开libpjproject-i386-Win32-vc14-Debug-Static.lib
- 我应该在 C++ 中何时/为什么使用 STATIC?
- 在VS2019项目中集成ImageMagick:x64-windows-static library
- 如何处理Boost Spirit X3导致Visual Studio 2019 "static initialization order fiasco"?
- "static char __ = []() -> char"的含义
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- 无法在 DLL 中链接 SDL2-static.lib
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- 错误:"cast"未命名类型void setCastDescription(std::string
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- C++线程"Call to non-static member function without an object argument"
- 出现这种错误的原因是什么"invalid use of non-static data member "
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- static是如何使用ClassA::m_variable处理所有类对象的
- 在[expr.static.cast]/4中,术语"一个可行函数"指的是什么