为什么 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 函数占用常量,则转换有效:
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
(。
对于非常量,函数将能够修改它,并且编译器必须将其传输回它来自的类型,这将导致各种问题,因此不允许/不可能。
相关文章:
- 强制转换为引用类型
- 如何将 int 引用安全地转换为长引用?
- C 样式转换引用
- 将通用引用强制转换为可调用的 void 指针,反之亦然
- 隐式重新解释引用时强制转换,没有警告/错误
- 右值引用转换后的地址更改
- 通过引用传递参数时C++类型转换
- 为什么我需要在转换构造函数上引用 this->?
- 枚举类的 C 样式强制转换到基础类型 char 的引用
- 转换指针引用的字符串
- 隐式可转换参数,但属于引用类型
- 转换引用对象的边界框?
- C++将引用转换为指针?
- C++ 引用是否在需要时隐式转换为值?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 从基类的共享指针向下转换到派生类的引用
- 为什么 const 允许在参数中隐式转换引用
- 与强制类型转换指针相比,在dynamic_cast中使用强制类型转换引用
- 动态强制转换引用和自动转换