名稱空間
變體
操作

std::ref, std::cref

來自 cppreference.com
 
 
 
函式物件
函式呼叫
(C++17)(C++23)
恆等函式物件
(C++20)
引用包裝器
refcref
(C++11)(C++11)
透明運算子包裝器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

舊繫結器和介面卡
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)  
(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
(直到 C++17*)(直到 C++17*)
(直到 C++17*)(直到 C++17*)

(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
 
定義於標頭檔案 <functional>
template< class T >
std::reference_wrapper<T> ref( T& t ) noexcept;
(1) (C++11 起)
(C++20 起為 constexpr)
template< class T >

std::reference_wrapper<T>

    ref( std::reference_wrapper<T> t ) noexcept;
(2) (C++11 起)
(C++20 起為 constexpr)
template< class T >
void ref( const T&& ) = delete;
(3) (C++11 起)
template< class T >
std::reference_wrapper<const T> cref( const T& t ) noexcept;
(4) (C++11 起)
(C++20 起為 constexpr)
template< class T >

std::reference_wrapper<const T>

    cref( std::reference_wrapper<T> t ) noexcept;
(5) (C++11 起)
(C++20 起為 constexpr)
template< class T >
void cref( const T&& ) = delete;
(6) (C++11 起)

函式模板 refcref 是輔助函式,它們生成 std::reference_wrapper 型別的物件,並使用 模板引數推導 來確定結果的模板引數。

T 可以是不完整型別。

(C++20 起)

目錄

[編輯] 引數

t - 對需要包裝的物件或 std::reference_wrapper 例項的左值引用

[編輯] 返回值

2) t
4) std::reference_wrapper<const T>(t)
5) t
3,6) 右值引用包裝器被刪除。

[編輯] 示例

#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

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 3146 C++11 解包過載有時導致錯誤 已始終有效

[編輯] 參閱

CopyConstructibleCopyAssignable 引用包裝器
(類模板) [編輯]