为什么const允许参数中引用的隐式转换? [英] Why does const allow implicit conversion of references in arguments?
问题描述
这听起来像是一个愚蠢的问题,但是我对以下行为感到困惑:
This may sound like a silly question, but I was confused about this following behaviour:
void funcTakingRef(unsigned int& arg) { std::cout << arg; }
void funcTakingByValue(unsigned int arg) { std::cout << arg; }
int main()
{
int a = 7;
funcTakingByValue(a); // Works
funcTakingRef(a); // A reference of type "unsigned int &" (not const-qualified)
// cannot be initialized with a value of type "int"
}
经过深思熟虑,这是有道理的,因为在通过值传递时会创建一个新变量并可以进行转换,但是在传递变量的实际地址时并没有那么多,就像在C ++中一次传递变量一样使其类型无法真正改变。我认为这与这种情况类似:
After thinking about it this kind of makes sense because in passing by value a new variable is created and conversion can be done, but not so much when passing the actual address of a variable, as in C++ once variables are made their type can't really change. I thought it's similar to this case:
int a;
unsigned int* ptr = &a; // A value of type int* cannot be used to
// initialise an entity of type "unsigned int*"
但是如果我使ref函数采用const,则转换有效:
But if I make ref function take a const the conversion works:
void funcTakingRef(const unsigned int& arg) { std::cout << arg; } // I can pass an int to this.
但是在指针的情况下是不一样的:
However not the same in the case of pointer:
const unsigned int* ptr = &a; // Doesn't work
我想知道这是什么原因。我以为我的推论是正确的,因为当通过值传递时进行隐式转换是有道理的,因为在C ++中,类型一旦创建就永远不会改变,就无法在引用上进行隐式转换。但这似乎不适用于const引用参数。
I'm wondering what the reason for this is. I thought my reasoning was right that implicit conversion when passing by value made sense as a new variable is made, whereas because in C++ types never change once created you can't get an implicit conversion on a reference. But this doesn't seem to apply in a const reference parameter.
推荐答案
这是暂时的。
引用不能直接绑定到具有不同类型的变量。对于这两种情况, int
需要转换为 unsigned int
,这是临时的(从 int
)。临时 unsigned int
可以绑定到对 const
的左值引用(即 const unsigned int& ;
)(并且其生存期延长到引用的生存期),但不能绑定到非常量的左值引用(即 unsigned int&
)。例如,
References can't bind to variables with different type directly. For both cases int
needs to be converted to unsigned int
, which is a temporary (copied from int
). The temporary unsigned int
could be bound to lvalue-reference to const
(i.e. const unsigned int&
), (and its lifetime is extended to the lifetime of the reference,) but can't be bound to lvalue-reference to non-const (i.e. unsigned int&
). e.g.
int a = 7;
const unsigned int& r1 = a; // fine; r1 binds to the temporary unsigned int created
// unsigned int& r2 = a; // not allowed, r2 can't bind to the temporary
// r2 = 10; // trying to modify the temporary which has nothing to do with a; doesn't make sense
这篇关于为什么const允许参数中引用的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!