GCC和Clang都拒绝接受以下代码中的C风格演员.
http://coliru.stacked-crooked.com/a/c6fb8797d9d96a27
struct S {
typedef const int* P;
operator P() { return nullptr; }
};
int main() {
int* p1 = const_cast<int*>(static_cast<const int*>(S{}));
int* p2 = (int*)(S{});
}
Run Code Online (Sandbox Code Playgroud)
main.cpp: In function 'int main()':
main.cpp:7:25: error: invalid cast from type 'S' to type 'int*'
int* p2 = (int*)(S{});
main.cpp:7:15: error: cannot cast from type 'S' to pointer type 'int *'
int* p2 = (int*)(S{});
^~~~~~~~~~~
但是,根据标准,C风格的演员表可以执行a static_cast后跟a 执行的转换const_cast.这段代码是否格式良好?如果没有,为什么不呢?
以下代码如何在C++中工作?这合乎逻辑吗?
const int &ref = 9;
const int &another_ref = ref + 6;
Run Code Online (Sandbox Code Playgroud)
为什么当非const引用不允许C++时,C++允许对const引用进行文字初始化?例如:
const int days_of_week = 7;
int &dof = days_of_week; //error: non const reference to a const object
Run Code Online (Sandbox Code Playgroud)
这可以通过以下事实来解释:非const引用可用于更改它所引用的变量的值.因此,C++不允许对const变量进行非const引用.
这可能是一个可能的解释吗?C++不允许:
int &ref = 7;
Run Code Online (Sandbox Code Playgroud)
因为这不符合逻辑,但是:
const int &ref = 7;
Run Code Online (Sandbox Code Playgroud)
几乎相当于:
const int val = 7;
Run Code Online (Sandbox Code Playgroud)
因此,const变量允许进行文字初始化.
PS:我正在研究Lippman的C++入门.
下面代码的输出产生:
void doit(const T1 &, const T2 &) [T1 = unsigned long, T2 = int]
t1 == t2
t1 == (T1)t2
t1 != (T1&)t2
t1 == (T1&&)t2
Run Code Online (Sandbox Code Playgroud)
我知道这个t1 == t2案子只是一个不可或缺的促销活动.
第二种情况t1 == (T1)t2是相同的,只是明确的.
第三种情况t1 == (T1&)t2必须是reinterpret_cast某种形式......但是,进一步的解释会有所帮助.
第四种情况t1 == (T1&&)t2是我坚持的.我在问题的标题中加入了"临时实现"这个术语,因为这是我能得到某种答案的最接近的.
有人可以查看这四个案例吗?
码:
#include <iostream>
template <typename T1, typename T2>
void doit(const T1& t1, const T2& t2) {
std::cout << __PRETTY_FUNCTION__ << '\n';
if (t1 == t2) {
std::cout << "t1 == …Run Code Online (Sandbox Code Playgroud) 考虑:
float const& f = 5.9e-44f;
int const i = (int&) f;
Run Code Online (Sandbox Code Playgroud)
根据expr.cast/4这应该被视为,为了:
- 一
const_cast,- 一
static_cast,- a
static_cast后跟 aconst_cast,- 一
reinterpret_cast,或- a
reinterpret_cast后跟 aconst_cast,
显然 astatic_cast<int const&>后跟 aconst_cast<int&>是可行的,并且将导致int值为0 的 a。但是所有编译器都初始化i为42,表明它们采用了最后一个选项reinterpret_cast<int const&>后跟const_cast<int&>。为什么?
相关:在 C++ 中,C 风格的强制转换可以调用转换函数然后抛弃常量吗?,为什么 (int&)0 格式错误?, C++ 规范是否说明了如何在 static_cast/const_cast 链中选择类型以用于 C 样式强制转换?,用 (float&)int …