84669 人學習
152542 人學習
20005 人學習
5487 人學習
7821 人學習
359900 人學習
3350 人學習
180660 人學習
48569 人學習
18603 人學習
40936 人學習
1549 人學習
1183 人學習
32909 人學習
闭关修行中......
C++裡引用其實只是受限的指針,只是在語意上限制不能對引用這一受限的指針做一些指針能做的操作:重新賦值,拷貝,++,--(暫時還沒想到其他的),並限制不允許為空,以提高安全性,可以理解為是編譯器對指標的一種保護模式。
那麼,考慮什麼時候該使用引用,又什麼時候該使用指標呢?我認為有幾點:
引用優先
凡是能用引用代替指標的都用引用。
指標是允許為空的,而引用不允許。
const stock* top(...) { return NULL; }
當然,這種情況下你還是可以堅持使用引用,然後空物件的情況下可以用throw exception的方式來表達:
const stock& top(...) { throw null_top_stock_exception(); }
合理使用語意暗示,指標暗示擁有(has),引用暗示關聯(use):
car has a wheel
car
wheel
class wheel {}; class car { wheel* _wheel; public: car() : _wheel(NULL) {}; void set_wheel(wheel* wheel) { _wheel = wheel; }; };
trip use a car:
trip
class trip { const car& _car public: trip(const car& car) : _car(car) {}; };
當然,也是有例外,如果在trip的生存週期裡,關聯的_car是要求可變的,那就只能使用指針了(因為引用不可以重新賦值):
class trip { const car* _car public: trip(const car* car) : _car(car) {}; void set_car(const car* car) : _car(car) { _car = car; }; };
否則,堅持使用引用的話,想更改_car的指向,就只能重新建構一個新的trip了。
容器中不可保存引用,只能用指標(我猜主要是因為引用被限制了重新賦值及拷貝操作):
std::vector<car> cars; // OK std::vector<car*> cars; // OK std::vector<car&> cars; // ERROR
最後,隨時可以把引用轉換成指標:
class maintainer { public: void maintain(car& car) { car* p = &car; // play with pointer 'p' } };
但一定要注意情景,這裡car只是傳進來供maintain方法使用(引用暗示use關係),取指針操作雖然不優雅,尚可以接受,但千萬要注意把指針保存下來使用的情況:
class maintainer { car* _last_car; public: void maintain(car& car) { car* _last_car = &car; // ... } void review_last_maintain() { // play with "_last_car" } };
在退出maintain方法後,_last_car所指向的物件是很有可能會被釋放的。
const講起來就是個無底洞舉個引用的例子吧
#include <iostream> #include<string> using namespace std; class Stu { public: Stu(string name, int age) // :name(name),age(age) { this->name = name; this->age = age; } Stu & Add() //Stu * const & Add() { this->age++; return *this; // return this;//this 指针是const类型 } void display() { cout << name << " : " << age << endl; } private: string name; int age; }; int main() { Stu s("xiaoming", 20); s.display(); s.Add().Add().Add().Add().Add(); //Add函数返回引用的好处是,你可以进行连加或者比如运算符重载返回引用类型进行连等于运算 //s.Add()->Add()->Add()->Add(); s.display(); return 0; }
指標的話,允許return NULL,引用的話不行。
C++裡引用其實只是受限的指針,只是在語意上限制不能對引用這一受限的指針做一些指針能做的操作:重新賦值,拷貝,++,--(暫時還沒想到其他的),並限制不允許為空,以提高安全性,可以理解為是編譯器對指標的一種保護模式。
那麼,考慮什麼時候該使用引用,又什麼時候該使用指標呢?我認為有幾點:
引用優先
指標是允許為空的,而引用不允許。
當然,這種情況下你還是可以堅持使用引用,然後空物件的情況下可以用throw exception的方式來表達:
合理使用語意暗示,指標暗示擁有(has),引用暗示關聯(use):
car
has awheel
trip
use acar
:當然,也是有例外,如果在trip的生存週期裡,關聯的_car是要求可變的,那就只能使用指針了(因為引用不可以重新賦值):
否則,堅持使用引用的話,想更改_car的指向,就只能重新建構一個新的trip了。
容器中不可保存引用,只能用指標(我猜主要是因為引用被限制了重新賦值及拷貝操作):
最後,隨時可以把引用轉換成指標:
但一定要注意情景,這裡car只是傳進來供maintain方法使用(引用暗示use關係),取指針操作雖然不優雅,尚可以接受,但千萬要注意把指針保存下來使用的情況:
在退出maintain方法後,_last_car所指向的物件是很有可能會被釋放的。
const講起來就是個無底洞
舉個引用的例子吧
指標的話,允許return NULL,引用的話不行。