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



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

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 函数占用常量,则转换有效:

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++类型中,一旦创建就永远不会更改,因此您无法在引用上进行隐式转换。但这似乎不适用于常量引用参数。

重点是暂时的。

引用不能直接绑定到不同类型的变量。对于这两种情况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

const &允许编译器生成一个临时变量,该变量在调用后被丢弃(并且函数无法更改它,因为它是const(。
对于非常量,函数将能够修改它,并且编译器必须将其传输回它来自的类型,这将导致各种问题,因此不允许/不可能。

最新更新