简体   繁体   English

C++ 左值引用

[英]C++ lvalue references

So recently I revisited references on the type declaration but I didn't quite understand them.所以最近我重新访问了有关类型声明的参考资料,但我不太理解它们。

Consider this dummy code:考虑这个虚拟代码:

int ia = 10;
int& ref = ia;

Now, my questions are:现在,我的问题是:

  1. how do these int& ref work internally, does it mean here that the address of ref is assigned the address of ia and thus equal to &ia if not then what does the compiler do upon seeing these references?这些int& ref在内部是如何工作的,这是否意味着ref的地址被分配给ia的地址,因此等于&ia如果不是,那么编译器在看到这些引用时会做什么?
  2. Why aren't these references compiled in a c++ program?为什么这些引用没有编译到 c++ 程序中?

You don't have to think of addresses at all.您根本不必考虑地址。 ref is just another name for ia , or put another way, ref is an alias to ia . ref只是ia的另一个名称,或者换句话说, refia的别名。 Just syntactic sugar for your code.只是代码的语法糖。

The compiler in this case doesn't have to do much at all, just keep track of when the code contains ref , replace it with ia .在这种情况下,编译器根本不需要做太多事情,只需跟踪代码何时包含ref ,将其替换为ia

C++ standard doesn't specify how reference should be implemented by the compiler. C++ 标准没有指定编译器应该如何实现引用。 A lot of people think they are just aliases, but in fact, under the hood they are just implemented as const pointers.很多人认为它们只是别名,但实际上,在幕后它们只是作为const指针实现的。

C++ references are const pointers under the hood. C++ 引用是引擎盖下的const指针。 So:所以:

int ia = 10;
int& ref = ia;
ref++; // ia is 11 now

might be converted by the compiler to:可能会被编译器转换为:

int ia = 10;
int* const ref = ia;
(*ref)++; // ia is 11 now

They need initialization because constants must be initialized.它们需要初始化,因为常量必须被初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM