[英]how the binding of const type works in c++?
why this binding is ok为什么这个绑定没问题
int main()
{
double d = 4.56;
const int &r = d;
return 0;
}
but this is not但这不是
int main()
{
double d = 4.56;
int &r = d;
return 0;
}
can anyone explain me while the first one compile but second one shows error任何人都可以在第一个编译但第二个显示错误时向我解释
When you bind to a converted type (the double
has to be converted to an int
), you get a prvalue, since the converted int
is a temporary with no address in memory.当您绑定到转换后的类型(必须将
double
转换为int
)时,您会得到一个纯右值,因为转换后的int
是临时的,在 memory 中没有地址。 Therefore, binding a regular reference to it doesn't work, because they can only bind to glvalues.因此,绑定对它的常规引用是行不通的,因为它们只能绑定到 glvalues。
const
type references can bind to prvalues, so the first one compiles still. const
类型引用可以绑定到纯右值,所以第一个仍然可以编译。 Source: https://en.cppreference.com/w/cpp/language/value_category资料来源: https://en.cppreference.com/w/cpp/language/value_category
An int
reference cannot be bound to an object of type double
, because the types mismatch. int
引用不能绑定到double
类型的 object,因为类型不匹配。
So in order to make the initialization of the reference work at all, a new temporary object of the correct type int
must be created.因此,为了使引用的初始化完全起作用,必须创建一个正确类型
int
的新临时 object。 This is possible because there is an implicit conversion sequence from double
to int
.这是可能的,因为存在从
double
到int
的隐式转换序列。
The reference should then bind to this temporary, ie to a rvalue expression, but only const
lvalue references are allowed to bind to rvalues.然后引用应该绑定到这个临时的,即右值表达式,但只有
const
左值引用才允许绑定到右值。 Non- const
lvalue references are not allowed to do that, making the second program ill-formed.不允许非
const
左值引用这样做,从而使第二个程序格式错误。
Note that in the first program, although the reference is bound to a temporary object that would usually be destroyed at the end of the full-expression that it was created in, binding to a reference extends the lifetime of that temporary object to the lifetime of the reference.请注意,在第一个程序中,虽然引用绑定到一个临时 object,该临时 object 通常会在创建它的完整表达式结束时被销毁,但绑定到引用会将该临时 object 的生命周期延长到参考资料。 So using
r
in the first program is actually ok.所以在第一个程序中使用
r
其实是可以的。
However, access through r
will not refer to d
, but to that new temporary object that is independent of d
, which may be surprising, and therefore I think it is not a good idea to write like that.但是,通过
r
访问不会引用d
,而是引用独立于d
的新临时 object ,这可能令人惊讶,因此我认为这样写不是一个好主意。 Use auto&
or const auto&
to make sure that r
will certainly refer to d
and that there is never any implicit conversion happening due to a type mismatch.使用
auto&
或const auto&
确保r
肯定会引用d
并且不会由于类型不匹配而发生任何隐式转换。 If you want the conversion, just use int
instead of a reference to int
.如果您想要转换,只需使用
int
而不是对int
的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.