|
pointer 和 reference 是我们的老朋友了。大家的最粗浅的基本常识就是,尽量用reference and pointer 防止copy 过度浪费资源。另一个常识就是 reference and pointer 差不多,基本上可以混用在很多情况下。一般的解决问题的方式是只要compile 不出错,就是OK的,如果出错了,就& and *换换看,总有一个地方可以通过,combination 就是那么多。
这一篇文章就是粗浅的总结一下pointer and reference的用法和区别。要做到写代码的时候心里清楚,不要一个一个符号尝试。
今天在网上看到一个心法说的很牛逼,Pointer 三心二意,reference 从一而终。
首先 int* 是一个pointer,这个变量自己是一个内存地址,他可以指向XX。所以他自己的地址不重要,他的内容也不重要,他的内容里面的地址很重要。
int* x; 就是一个variable 他存储了一个内存地址,这个内存地址指向一个int. pointer 是可以改的,你可以让他指向其他的变量,或者不指向任何变量。
int& x; 这个是一个reference。他可以认为是一个变量的nick name. 所以int& x 在initialize 的时候必须跟一个variable 相挂钩,不能为null. 同时他也不能更改,不能指向其他的variable. 除此之外,跟pointer 是一样的。
我们来看一个长的例子
#include <mutex>
#include <thread>
#include <iostream>
using namespace std;
struct Demo {
int number = 5;
};
int main() {
int x = 5;
int y = 6;
int* xPtr = &x; // pointer is mem address of var x
cout << *xPtr << endl; // should be the same as x, which is 5
xPtr = &y; // repoint to y
cout << *xPtr << endl; // it should be y which is 6
cout << xPtr << endl;
cout << &y << endl; // xPtr value should be the address of y
cout << &xPtr << endl; // it should be the address of the pointer which we do not care
// you can use pointer to change the value of the var
*xPtr = 99;
cout << y << endl; // y is changed to 99
cout << &#34;------ end of pointer section demo ------&#34; << endl; //
int& xRef = x ;
// NOTE: &xRef = y; // this will trigger compile error
cout << x << endl;
xRef = y; // xRef is the reference of x, thus now x and y are the same value
cout << x << endl;
xPtr ++ ; // move to the next mem location
xRef++; // x++ which makes x to 100
cout << x << endl;
// compare address they should be the same
cout << &xRef << endl;
cout << &x << endl;
cout << &#34;------- end ref section demo -------&#34; << endl;
Demo d {};
Demo* dPtr = & d;
cout << dPtr -> number << endl;
Demo& dRef = d;
cout << dRef.number << endl;
} |
|