Namespaces
Variants

std:: ref, std:: cref

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until 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 起)

函数模板 ref cref 是辅助函数,用于生成类型为 std::reference_wrapper 的对象,通过 模板实参推导 来确定结果的模板参数。

T 可以是非完整类型。

(since 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; // 递增函数对象中存储的 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

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 3146 C++11 解包重载有时会导致错误 设为始终有效

参见

CopyConstructible CopyAssignable 引用包装器
(类模板)