本篇內容介紹了“C++中什么時候傳遞const參照”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
對于輸入參數來說,拷貝代價小的傳值,其他傳遞const參照
兩種方式都可以讓調用者知道函數不會修改參數并且都可以通過右值初始化。
什么是“拷貝代價小”和機器架構有關,但是2到3個字(雙精度數,指針,引用)通常最適合傳值。如果拷貝代價小,沒有方法可以超過拷貝的簡單和安全,另外,對于小對象(不超過2到3個字)來說,由于函數不需要額外間接訪問,因此傳值會比傳址的速度更快。
Example(示例)
void f1(const string& s); // OK: pass by reference to const; always cheap
void f2(string s); // bad: potentially expensive
void f3(int x); // OK: Unbeatable
void f4(const int& x); // bad: overhead on access in f4()
(只)對于高級的用法,需要優化為向輸入參數傳遞右值引用的情況有:
If the function is going to unconditionally move from the argument, take it by &&
. See F.18.
如果函數會無條件的移動參數的內容,使用&&。參考F.18
If the function is going to keep a copy of the argument, in addition to passing by const&
(for lvalues), add an overload that passes the parameter by &&
(for rvalues) and in the body std::move
s it to its destination. Essentially this overloads a "will-move-from"; see F.18.
如果函數會管理一個參數的拷貝,除了使用功能const&(對于左值)以外,增加一個使用&&(對于右值)傳遞參數的重載函數并且在內部使用std::move移動參數內容到目標上。本質上這個重載是一個“將要移動形式”;參考F.18
In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. See F.19.
對于
特殊場合,例如多重“輸入+拷貝”參數,考慮使用完美的forward。
Example(示例)
int multiply(int, int); // just input ints, pass by value
// suffix is input-only but not as cheap as an int, pass by const&
string& concatenate(string&, const string& suffix);
void sink(unique_ptr<widget>); // input only, and moves ownership of the widget
避免使用“只有高手才懂的技術”,例如:
Passing arguments as T&&
"for efficiency". Most rumors about performance advantages from passing by &&
are false or brittle (but see F.18 and F.19).
為了提高效率而使用T&&。許多通過傳遞&&獲得性能優勢的傳言都是假的或者脆弱的。
Returning const T&
from assignments and similar operations
通過復制或者類似操作返回const T&
Example(示例)
假設Matrix實現了移動操作(例如使用std::vector保管元素)
Matrix operator+(const Matrix& a, const Matrix& b)
{
Matrix res;
// ... fill res with the sum ...
return res;
}
Matrix x = m1 + m2; // move constructor
y = m3 + m3; // move assignment
返回值優化不會處理賦值的情況,但是移動賦值會。
可以假設引用參照的是有效對象(語言準則)。不存在(合理的)“空引用”。如果需要可選值概念,使用指針,std::optional或者特殊值表示“沒有值”。
(Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than 2 * sizeof(void*)
. Suggest using a reference to const
instead.
(簡單)((基本準則)) 當傳值的大小超過2*sizeof(void*)時,報警。建議使用const引用。
(Simple) ((Foundation)) Warn when a parameter passed by reference to const
has a size less than 2 * sizeof(void*)
. Suggest passing by value instead.
(簡單)((基本準則))當小于2*sizeof(void*)的參數使用const傳址時,報警。
(Simple) ((Foundation)) Warn when a parameter passed by reference to const
is move
d.
(簡單)((基本準則))當使用const傳址的參數的內容被移動時,報警。
“C++中什么時候傳遞const參照”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。