c++中ref的作用示例解析
正文
C++11 中引入 std::ref
用于取某個變量的引用,這個引入是為了解決一些傳參問題。
我們知道 C++ 中本來就有引用的存在,為何 C++11 中還要引入一個 std::ref
了?主要是考慮函數(shù)式編程(如 std::bind
)在使用時,是對參數(shù)直接拷貝,而不是引用。下面通過例子說明
示例1:
#include <functional> #include <iostream> void f(int& n1, int& n2, const int& n3) { std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; ++n1; // increments the copy of n1 stored in the function object ++n2; // increments the main()'s n2 // ++n3; // compile error } int main() { int n1 = 1, n2 = 2, n3 = 3; std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3)); n1 = 10; n2 = 11; n3 = 12; std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; bound_f(); std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; }
輸出:
Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12
上述代碼在執(zhí)行 std::bind
后,在函數(shù) f()
中n1
的值仍然是 1,n2
和 n3
改成了修改的值,說明 std::bind
使用的是參數(shù)的拷貝而不是引用,因此必須顯示利用 std::ref
來進行引用綁定。具體為什么 std::bind
不使用引用,可能確實有一些需求,使得 C++11 的設(shè)計者認為默認應(yīng)該采用拷貝,如果使用者有需求,加上 std::ref
即可。
#include <thread> #include <iostream> #include <string> void threadFunc(std::string &str, int a) { str = "change by threadFunc"; a = 13; } int main() { std::string str("main"); int a = 9; std::thread th(threadFunc, std::ref(str), a); th.join(); std::cout<<"str = " << str << std::endl; std::cout<<"a = " << a << std::endl; return 0; }
該程序創(chuàng)建一個線程 th
,調(diào)用帶有兩個參數(shù)的 threadFunc
函數(shù):一個是 std::string
對象 str
的引用,另一個是整數(shù) a
。函數(shù) threadFunc
修改字符串 str
為 "change by threadFunc",但不修改整數(shù) a
。最后在主線程中輸出 str
和 a
的值。
輸出:
str = change by threadFunc
a = 9
可以看到,和 std::bind 類似,多線程的 std::thread 也是必須顯式通過 std::ref 來綁定引用進行傳參,否則,形參的引用聲明是無效的。
總結(jié)
std::ref
是一個 C++ 標準庫函數(shù)模板,它將對象的引用轉(zhuǎn)換為可復(fù)制的可調(diào)用對象。
std::ref
用于將對象的引用傳遞給函數(shù)或線程等可調(diào)用對象的參數(shù)。如果不使用 std::ref
,那么函數(shù)或線程會將對象的副本傳遞給可調(diào)用對象的參數(shù),這可能會導(dǎo)致無法預(yù)期的結(jié)果,因為對該副本的修改不會影響原始對象。通過使用 std::ref
,可以確??烧{(diào)用對象引用的是原始對象,因此對該對象的修改將影響原始對象。
需要注意的是,使用 std::ref
前必須確保原始對象的生命周期至少與可調(diào)用對象相同,否則會導(dǎo)致懸空引用。另外,std::ref
不能用于將指向臨時對象或?qū)⑦^時對象的引用傳遞給可調(diào)用對象。
總之,std::ref
的作用是將對象的引用轉(zhuǎn)換為可復(fù)制的可調(diào)用對象,使得在函數(shù)或線程等可調(diào)用對象中引用原始對象,而不是其副本。
以上就是c++中ref的作用示例解析的詳細內(nèi)容,更多關(guān)于c++ ref作用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C語言數(shù)據(jù)結(jié)構(gòu)與算法之鏈表(一)
鏈表是線性表的鏈式存儲方式。鏈表的內(nèi)存是不連續(xù)的,前一個元素存儲地址的下一個地址中存儲的不一定是下一個元素。小編今天就將帶大家深入了解一下鏈表,快來學(xué)習(xí)吧2021-12-12VSCode (Visual Studio Code) V1.43.0下載并設(shè)置成中文語言的方法
Visual Studio Code是一款免費開源的現(xiàn)代化輕量級代碼編輯器,支持語法高亮、智能代碼補全、自定義熱鍵、括號匹配、代碼片段、代碼對比 Diff、GIT 等特性,這篇文章主要介紹了VSCode (Visual Studio Code) V1.43.0下載并設(shè)置成中文語言,需要的朋友可以參考下2020-03-03