CppDS.com

C++ 98 11 14 17 20 手册

std::ref, std::cref

来自cppreference.com
< cpp‎ | utility‎ | functional
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等字符串转换
(C++17)
(C++17)
 
函数对象
函数包装
(C++11)
(C++11)
部分函数应用
(C++11)
(C++20)
函数调用
(C++17)
恒等函数对象
(C++20)
引用包装
refcref
(C++11)(C++11)
运算符包装
取反器
(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>
(1)
template< class T >
std::reference_wrapper<T> ref(T& t) noexcept;
(C++11 起)
(C++20 前)
template< class T >
constexpr std::reference_wrapper<T> ref(T& t) noexcept;
(C++20 起)
(2)
template< class T >
std::reference_wrapper<T> ref( std::reference_wrapper<T> t ) noexcept;
(C++11 起)
(C++20 前)
template< class T >
constexpr std::reference_wrapper<T> ref( std::reference_wrapper<T> t ) noexcept;
(C++20 起)
template <class T>
void ref(const T&&) = delete;
(3) (C++11 起)
(4)
template< class T >
std::reference_wrapper<const T> cref( const T& t ) noexcept;
(C++11 起)
(C++20 前)
template< class T >
constexpr std::reference_wrapper<const T> cref( const T& t ) noexcept;
(C++20 起)
(5)
template< class T >
std::reference_wrapper<const T> cref(std::reference_wrapper<T> t) noexcept;
(C++11 起)
(C++20 前)
template< class T >
constexpr std::reference_wrapper<const T> cref(std::reference_wrapper<T> t) noexcept;
(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) std::ref(t.get())
4) std::reference_wrapper<const T>(t)
5) std::cref(t.get())
3,6) 右值引用包装器被删除。

示例

#include <functional>
#include <iostream>
 
void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    ++n1; // 增加存储于函数对象的 n1 副本
    ++n2; // 增加 main() 的 n2
    // ++n3; // 编译错误
}
 
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

参阅

可复制构造 (CopyConstructible) 可复制赋值 (CopyAssignable) 的引用包装器
(类模板)
关闭