为什么 const 允许参数中引用的隐式转换?

2023-11-23

这听起来像是一个愚蠢的问题,但我对以下行为感到困惑:

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 引用参数。


重点是暂时的。

引用不能直接绑定到不同类型的变量。对于这两种情况int需要转换为unsigned int,这是一个临时的(复制自int)。临时的unsigned int可以绑定到左值引用const (i.e. const unsigned int&),(并且它的生命周期延长到引用的生命周期,)但不能绑定到非 const 的左值引用(即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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 const 允许参数中引用的隐式转换? 的相关文章

随机推荐