值类型为reference_wrapper时的unordered_map值赋值

时间:2017-10-06 22:55:21

标签: c++ c++11 reference 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  

有人可以解释我做错了吗?

1 个答案:

答案 0 :(得分:5)

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

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

要使两个示例更相同,您需要使用std::unordered_map::insertstd::unordered_map::emplace