命名空间
变体
操作

std::ref, std::cref

来自 cppreference.cn
< cpp‎ | utility‎ | functional
 
 
 
函数对象
函数调用
(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 起)
(constexpr 自 C++20 起)
template< class T >

std::reference_wrapper<T>

    ref( std::reference_wrapper<T> t ) noexcept;
(2) (自 C++11 起)
(constexpr 自 C++20 起)
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 起)
(constexpr 自 C++20 起)
template< class T >

std::reference_wrapper<const T>

    cref( std::reference_wrapper<T> t ) noexcept;
(5) (自 C++11 起)
(constexpr 自 C++20 起)
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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 3146 C++11 解包重载有时会导致错误 使其始终有效

[编辑] 参见

CopyConstructibleCopyAssignable 引用包装器
(类模板) [编辑]