可能的重复:
为什么允许将指针强制转换为引用? https://stackoverflow.com/questions/5924248/why-is-it-allowed-to-cast-a-pointer-to-a-reference
为什么会这样编译:
class Bar {};
int main() {
Bar i;
Bar *b = &i;
typedef const Bar& type;
type t = type(b);
}
G++ (4.5 http://www.ideone.com/huvDG,4.7 快照),Comeau http://www.comeaucomputing.com/tryitout/和 MSVC 都很高兴,但警告未使用的变量。
编译器认为这意味着什么?是UB吗?为什么不是错误呢?
我认为这应该是一个错误,因为我不小心犯了一个Bar*
into const Bar&
无需解除引用或疯狂的强制转换。我认为这一切都是完全安全的。
C 风格的强制转换依次尝试不同的 C++ 强制转换类型:
[C++11: 5.4/5]:
执行的转换
- a
const_cast
(5.2.11),
- a
static_cast
(5.2.9),
- a
static_cast
随后是一个const_cast
,
-
a
reinterpret_cast
(5.2.10), or
- a
reinterpret_cast
随后是一个`const_cast
,
可以使用显式类型转换的强制转换表示法来执行。适用相同的语义限制和行为,但在以下情况下执行 static_cast 时,即使基类不可访问,转换也是有效的:
然后遵循各种复杂的规则,我懒得去详细解析。
你会得到必要的警告,说这是一个愚蠢的演员阵容,但既然这是你所要求的,那就是所尝试的。
与之比较:
class Bar {};
int main() {
Bar *b = 0;
typedef const Bar& type;
const type t = static_cast<type>(b);
}
// In function 'int main()':
// Line 6: error: invalid static_cast from type 'Bar*' to type 'const Bar&'
// compilation terminated due to -Wfatal-errors.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)