pointer 和 reference的不同使用情况

来源:互联网 发布:淘宝摄影服务市场收费 编辑:程序博客网 时间:2024/05/16 08:17

读more effective c++ 注意到一个以前没有注意的细节问题:

pointer 和 reference 都是地址形式,他们在使用上有什么区别呢?

下面的例子很好的说明了两者的区别:

reference:

void printDouble(const double &rd){

  cout<<rd; //no need to test rd, it must refer to a double

}

pointer:

void printDouble(const double *pd){

  if(pd){

    cout<< *pd;   // need to check for null pointer problem

  }

}

 

另一个重要的区别是 pointer 可以重新指向不同的对象, 而reference永远指向它初始化时候的对象。

string s1("Nancy");

string s2(“Clancy”);

string &rs = s1;

string *ps = &s1;

rs = s2; //rs still refers to s1, but the content in s1 is changed to Clancy

ps = &s2; // ps now point to s2, but s1 is unchanged.