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 は不完全型であってもよい。

(C++20以降)

目次

パラメータ

t - ラップする必要があるオブジェクトへのlvalue参照、または std::reference_wrapper のインスタンス

戻り値

2) t
4) std:: reference_wrapper < const T > ( t )
5) t
3,6) rvalue reference wrapperは削除されました。

#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++規格に対して遡及的に適用されました。

DR Applied to Behavior as published Correct behavior
LWG 3146 C++11 unwrapping overloads sometimes led to error made always valid

関連項目

CopyConstructible および CopyAssignable 参照ラッパー
(クラステンプレート)