Reference_wrapper:Push_back有效,但没有分配

Shi*_*bli -2 c++ stdvector c++11 reference-wrapper

在下面的代码,push_back()std::refstd::vector<reference_wrapper<Type>>行之有效然而,分配std::refreference_wrapper<Type>不起作用.为什么?

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

struct Type {};

int main()
{
    Type t1;

    vector<reference_wrapper<Type>> t2;
    t2.push_back( ref(t1) ); // OK

    //reference_wrapper<Type> t3; // error: no matching function for call to std::reference_wrapper<Type>::reference_wrapper()’
    //t3 = ref(t1);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 5

该错误消息告诉您实际问题是引用包装器没有默认构造函数.您可以将一个引用包装器分配给另一个,但是您不能先创建一个"空"引用包装器,然后通过赋值给它一个值.