从指针typedef常量引用 [英] Typedef const reference from a pointer
问题描述
为什么编译:
class Bar {};
int main() {
Bar i;
Bar *b = &i;
typedef const Bar& type;
type t = type(b);
}
G ++( 4.5 ,4.7个快照), Comeau 和MSVC所有人都很高兴但警告未使用的变量。
G++ (4.5, 4.7 snapshots), Comeau and MSVC all are happy but warn about unused variables.
编译器认为它意味着什么?是UB吗?为什么不是一个错误?
What does the compiler think it means? Is it UB? Why isn't it an error?
我认为这应该是一个错误,因为我不小心做了一个 Bar *
进入 const Bar&
,无需取消引用或疯狂投放。
I think it should be an error because I've accidentally made a Bar*
into const Bar&
without dereferencing or crazy casts. I thought every part of this was completely safe.
推荐答案
C风格的转换会依次尝试不同的C ++类型: p>
A C-style cast tries different C++ cast types in turn:
[C ++ 11:5.4 / 5]:
- a
const_cast
(5.2.11) li>
- a
static_cast
(5.2.9), - a
static_cast
后跟const_cast
, - a
reinterpret_cast
(5.2.10)或 - a
reinterpret_cast
可以使用显式类型转换的转换符号执行const_cast ,
- a
const_cast
(5.2.11), - a
static_cast
(5.2.9), - a
static_cast
followed by aconst_cast
, - a
reinterpret_cast
(5.2.10), or - a
reinterpret_cast
followed by a`const_cast
,
>相同的语义限制和行为适用,除了在以下情况下执行static_cast时,即使基类不可访问,转换也是有效的:
can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply, with the exception that in performing a static_cast in the following situations the conversion is valid even if the base class is inaccessible:
- [..]
然后遵循各种复杂规则,
And then follows various complex rules that I can't be bothered to parse in detail.
你得到必要的警告,这是一个愚蠢的施法,但因为它是你要求的是它的尝试。
You get the requisite warnings that it's a stupid cast, but since it's what you asked for it's what's attempted.
比较:
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.
这篇关于从指针typedef常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!