unordered_map 值类型为 reference_wrapper 时的赋值

unordered_map value assignation when value type is reference_wrapper

我正在试验 std::reference_wrapper。我不明白为什么以下内容适用于 std::vector 但不适用于 std::unordered_map:

#include <functional>
#include <vector>
#include <unordered_map>

using namespace std;

int main()
{
  vector<vector<long>> x;

  vector<reference_wrapper<vector<vector<long>>>> y;
  y.push_back(ref(x)); // OK

  unordered_map<string, reference_wrapper<vector<vector<long>>>> m;
  m["lol"] = ref(x); // NOT OK
}

这是我得到的编译错误

/usr/include/c++/7.2.0/tuple:1652:70: error: no matching function for call to ‘std::
reference_wrapper<std::vector<std::vector<long int> > >::reference_wrapper()’       
         second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
                                                                      ^
In file included from /usr/include/c++/7.2.0/bits/std_function.h:44:0,              
                 from /usr/include/c++/7.2.0/functional:58,                         
                 from test.cpp:1:         
/usr/include/c++/7.2.0/bits/refwrap.h:325:7: note: candidate: constexpr std::referen
ce_wrapper<_Tp>::reference_wrapper(const std::reference_wrapper<_Tp>&) [with _Tp = s
td::vector<std::vector<long int> >]       
       reference_wrapper(const reference_wrapper&) = default;                       
       ^~~~~~~~~~~~~~~~~
/usr/include/c++/7.2.0/bits/refwrap.h:325:7: note:   candidate expects 1 argument, 0
 provided            
/usr/include/c++/7.2.0/bits/refwrap.h:319:7: note: candidate: std::reference_wrapper
<_Tp>::reference_wrapper(_Tp&) [with _Tp = std::vector<std::vector<long int> >]     
       reference_wrapper(_Tp& __indata) noexcept                                    
       ^~~~~~~~~~~~~~~~~
/usr/include/c++/7.2.0/bits/refwrap.h:319:7: note:   candidate expects 1 argument, 0
 provided  

谁能解释一下我做错了什么?

m["lol"] 使用无序映射 operator[]。该运算符 return 是对地图中项目的引用。如果没有这样的项目,这是有问题的。

为了解决这个问题,它将默认构造它应该 return 的项目。这就是问题所在,因为 std::reference_wrapper 不是默认可构造的。

为了使这两个示例更加等同,您需要使用 std::unordered_map::insertstd::unordered_map::emplace