我一直使用返回引用來嘗試加快我的代碼並避免多個昂貴的複製操作。C++按參考多次返回
我有一個訪問成員函數,看起來像這樣:
std::string const& access_element(int index) const;
如果我有一個調用access_element()其他成員函數,我需要通過引用返回?
例如,
float const& access_element2(int index) const {
return atof(access_element(index));
}
與
float access_element2(int index) {
return atof(access_element(index));
}
您通過引用臨時返回值。在這種情況下,您的瓶頸就在於自己,而不是返回副本。 – 2012-01-18 14:27:50
我同意上面的註釋,但是您還需要查看http://en.wikipedia.org/wiki/Copy_elision,因爲編譯器有時可以做出更好的決策。 – rerun 2012-01-18 14:32:41
您不需要爲每個引用返回內置類型作爲優化,它們應該以每個副本高效傳遞。 – sbi 2012-01-18 14:55:53