我知道引用是语法糖,因此代码更容易读写.
但有什么区别?
以下答案和链接摘要:
NULL),而引用总是指对象.&obj + 5).澄清一个误解:
C++标准非常谨慎,以避免规定编译器如何实现引用,但每个C++编译器都将引用实现为指针.也就是说,声明如下:
Run Code Online (Sandbox Code Playgroud)int &ri = i;如果它没有完全优化,则分配与指针相同的存储量,并将地址
i放入该存储中.
因此,指针和引用都使用相同数量的内存.
作为基本规则,
有趣的读物:
我正在编写以下内容以通过引用传递指针.但是,当我尝试取消引用指针时,它会给出意想不到的值.
void passPointers(int* &a){
int p = 5;
a = &p;
}
int main(){
int x = 3;
int *y= &x;
cout<<"y is "<<y<<" *y is "<<*y<<endl;
passPointers(y);
//cout<<"y is "<<y<<" *y is "<<*y<<endl;//line a
cout<<" *y is "<<*y<<endl;//It returns 5
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释a行,它返回y的地址,*y返回一些未知的整数值.我打破了一些C++规范.我在编写此代码时使用了此链接.我正在使用g ++ 7.3.0
Node *&front在C++中下面的链表代码提取是什么意思?
FrontBackSpilit(head,a,b)
Node * FrontBackSpilit(Node * head, Node *&front, Node * &back)
Run Code Online (Sandbox Code Playgroud)