[英]Pass object to a function without wrapping it into std::ref, while argument is specified as a const reference
我有以下 c++ 代碼(只是一個簡單的問題示例)
#include <iostream>
#include <string>
#include <vector>
double get_first(const std::vector<double>& vec) {
return vec[0];
}
int main()
{
std::vector<double> some_vec = {1, 2};
std::cout << get_first(some_vec);
}
所以這里 function get_first
的參數是 const 引用,
而我傳遞整個向量some_vec
而不是將其包裝到 std::ref 中。 c++ 是否在此處復制完整的 object?
std::ref
不是為了那個。 它用於將現有引用轉換為 object,用於不能接受引用的情況,例如在std::vector<>
中。 這個想法是不能重新分配引用或將其設置為 null,因此 STL 容器中的內容(如移動等)不適用於原始引用。 很可能它在內部將包裝的引用轉換為指針。
在您的示例中,參數自動作為參考傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.