1. 程式人生 > 其它 >C++-std::ref

C++-std::ref

1、函數語言程式設計如std::bind、std::thread傳引數等使用時,是對引數直接拷貝而不是引用

如:

#include <functional>
#include <iostream>

void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: n1[" << n1 << "]    n2[" << n2 << "]    n3[" << n3 << "]" << std::endl;
    
++n1; // 增加儲存於函式物件的 n1 副本 ++n2; // 增加 main() 的 n2 //++n3; // 編譯錯誤 std::cout << "In function end: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl; } int main() { int n1 = 1, n2 = 1, n3 = 1; std::cout << "Before function: n1[
" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl; std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3)); bound_f(); std::cout << "After function: n1[" << n1 << "] n2[" << n2 << "
] n3[" << n3 << "]" << std::endl; }

結果:

Before function: n1[1]     n2[1]     n3[1]
In function: n1[1]    n2[1]    n3[1]
In function end: n1[2]     n2[2]     n3[1]
After function: n1[1]     n2[2]     n3[1]

n1是普通值傳遞;n2是引用傳遞;n3是const引用傳遞

參考:https://blog.csdn.net/lmb1612977696/article/details/81543802