條款20 :寧以pass-by-reference-to-const 替換pass-by-value

來源:互聯網
上載者:User

預設的情況下,C++是以by value方式傳遞對象至函數。函數實參都是以實際實參的複件為初始值,而調用端獲得的亦是函數傳回值的一個複件。這些複件系由對象的copy建構函式產出,這可能使得pass by value成為昂貴的操作。

 

       考慮下面的繼承體系:

 

classPerson{

public:

    Person();

    vitual~Person();

private:

    std::stringname;

    std::stringaddress;

};

 

classStudent:publicPerson{

public:

    Student();

    virtual~Student();

private:

    std::stringschoolName;

    std::stringschoolAddress;

 

};

 

 

 

現在有一個調用函數validateStudent,要調用一個Student實參並返回它是否有效?

boolvalidateStudent(Students);

Studentplato;

boolplatoIsOK=validateStudent(plato);

當上述調用發生時,會發生什麼事?我們用圖來說明:

        

 這樣結束了嗎?也不是這些吧。再看。

我們知道Student類繼承了Person類,而且兩個類中,都有string類類型的變數。My God

 

如果有一個方法可以迴避這些所有的建構函式與解構函式,那就好了。

有的,那就是以pass by reference to const.

boolvalidateStudent(constStudent&s);

注意,採用此種方式,還在以避免對象被切割。

voidprintStudent(Personp){

       cout<<schoolaName<<endl;//Error ,

}

Studentplato;

printStudent(plato); //本來想著要列印名字,但是由於對象被切割,會出現問題

 

 

為什麼用引用了之後,可以避免被切割?

如果窺視C++底層的話,你就會發現,reference往往是以指標實現出來的。因此,傳遞過來的指標。

如果你的參數是一個內建類型,則採用pass by value會比pass by reference to const更加有效率一些。

請記住:

l  盡量以pass by reference to const替換pass by value。前者通常比較高效,並可避免切割的問題。

l  以上規則並不適用於內建類型,以及STL的迭代器和函數對象。對它們而言,pass by value更加適當。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.