为什么 const 允许隐式转换参数中的引用?
Why does const allow implicit conversion of references in arguments?
这听起来像是一个愚蠢的问题,但我对以下行为感到困惑:
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++ 中一样,一旦创建了变量他们的类型不能真正改变。我认为它类似于这种情况:
int a;
unsigned int* ptr = &a; // A value of type int* cannot be used to
// initialise an entity of type "unsigned int*"
但是,如果我让 ref 函数采用 const,则转换有效:
void funcTakingRef(const unsigned int& arg) { std::cout << arg; } // I can pass an int to this.
但是在指针的情况下不一样:
const unsigned int* ptr = &a; // Doesn't work
我想知道这是什么原因。我认为我的推理是正确的,当创建一个新变量时,按值传递时的隐式转换是有意义的,而因为在 C++ 中,类型一旦创建就永远不会改变,所以不能对引用进行隐式转换。但这似乎不适用于 const 引用参数。
const &
允许编译器生成一个临时变量,该变量在调用后被丢弃(函数无法更改它,因为它是 const
)。
对于非常量,函数可以修改它,编译器必须将它转回它来自的类型,这会导致各种问题,所以它不是 allowed/possible.
重点是暂时的。
引用不能直接绑定到不同类型的变量。对于这两种情况,int
都需要转换为 unsigned int
,这是临时的(从 int
复制)。临时 unsigned int
可以绑定到 const
的左值引用(即 const unsigned int&
),(并且它的生命周期延长到引用的生命周期,)但不能绑定到对非常量的左值引用(即 unsigned int&
)。例如
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
这听起来像是一个愚蠢的问题,但我对以下行为感到困惑:
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++ 中一样,一旦创建了变量他们的类型不能真正改变。我认为它类似于这种情况:
int a;
unsigned int* ptr = &a; // A value of type int* cannot be used to
// initialise an entity of type "unsigned int*"
但是,如果我让 ref 函数采用 const,则转换有效:
void funcTakingRef(const unsigned int& arg) { std::cout << arg; } // I can pass an int to this.
但是在指针的情况下不一样:
const unsigned int* ptr = &a; // Doesn't work
我想知道这是什么原因。我认为我的推理是正确的,当创建一个新变量时,按值传递时的隐式转换是有意义的,而因为在 C++ 中,类型一旦创建就永远不会改变,所以不能对引用进行隐式转换。但这似乎不适用于 const 引用参数。
const &
允许编译器生成一个临时变量,该变量在调用后被丢弃(函数无法更改它,因为它是 const
)。
对于非常量,函数可以修改它,编译器必须将它转回它来自的类型,这会导致各种问题,所以它不是 allowed/possible.
重点是暂时的。
引用不能直接绑定到不同类型的变量。对于这两种情况,int
都需要转换为 unsigned int
,这是临时的(从 int
复制)。临时 unsigned int
可以绑定到 const
的左值引用(即 const unsigned int&
),(并且它的生命周期延长到引用的生命周期,)但不能绑定到对非常量的左值引用(即 unsigned int&
)。例如
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