far*_*oft 1 c++ pointers reference
引用是否被视为c ++中的指针?
int &x = y;
Run Code Online (Sandbox Code Playgroud)
x在内存中有空格吗?
依赖于实现而未由标准指定.编译器可以将其int &x视为指针,并在堆栈上为其创建空间; 它可能会挂在CPU寄存器中(因此不需要堆栈空间); 它可能会意识到它是现有对象的不同名称,只是在运行时将它们混为一谈.
这里有几种情况作为编译器如何使用引用执行不同操作的示例,具体取决于它的使用方式.
在像这样的功能:
int foo( int x )
{
int &y = x;
y += 2;
return y + x;
}
Run Code Online (Sandbox Code Playgroud)
像MSVC这样的编译器只会将y视为x的别名 - 同一变量的不同名称 - 并在编译期间用x静静地替换y的所有提及.因此,该函数实际上将被编译为就像它一样
int foo( int x )
{
x += 2;
return x + x;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用引用作为参数
int foo( int &x )
{
x += 2;
return x;
}
Run Code Online (Sandbox Code Playgroud)
然后x在内部实现为指针,并像任何其他参数一样传递到堆栈上的函数.编译器将其视为:
int foo( int *x )
{
(*x) += 2;
return *x;
}
Run Code Online (Sandbox Code Playgroud)
问题在于,您的问题的答案不仅取决于您使用的是哪种编译器,还取决于您正在编写的特定代码.它没有以任何方式指定.