C++ Difference between std::ref(T) and T&?

后端 未结 3 1282
既然无缘
既然无缘 2021-01-29 22:30

I have some questions regarding this program:

#include 
#include 
#include 
using namespace std;
template &l         


        
3条回答
  •  日久生厌
    2021-01-29 23:30

    A reference (T& or T&&) is a special element in C++ language. It allows to manipulate an object by reference and has special use cases in the language. For example, you cannot create a standard container to hold references: vector is ill formed and generates a compilation error.

    A std::reference_wrapper on the other hand is a C++ object able to hold a reference. As such, you can use it in standard containers.

    std::ref is a standard function that returns a std::reference_wrapper on its argument. In the same idea, std::cref returns std::reference_wrapper to a const reference.

    One interesting property of a std::reference_wrapper, is that it has an operator T& () const noexcept;. That means that even if it is a true object, it can be automatically converted to the reference that it is holding. So:

    • as it is a copy assignable object, it can be used in containers or in other cases where references are not allowed
    • thanks to its operator T& () const noexcept;, it can be used anywhere you could use a reference, because it will be automatically converted to it.

提交回复
热议问题