在Map中存储引用

8

我尝试将一个foo对象存储到std::reference_wrapper中,但最终遇到了编译器错误,我不理解这个错误的含义。

#include <functional>
#include <map>

struct foo
{
};

int main()
{
    std::map< int, std::reference_wrapper< foo > > my_map;
    foo a;
    my_map[ 0 ] = std::ref( a );
}

编译器错误信息比较冗长,但可以简化为以下内容:
error: no matching function for call to ‘std::reference_wrapper<foo>::reference_wrapper()’

我到底做错了什么?

std::reference_wrapper没有默认构造函数。 - Ron Tang
1个回答

7

std::reference_wrapper 不具备默认构造函数(否则它将是一个指针)。

my_map[0]

如果映射中不存在键为0的元素,将创建一个新的映射类型对象,并且该映射类型需要具有默认构造函数。如果您的映射类型不支持默认构造,请使用insert()方法:

my_map.insert(std::make_pair(0, std::ref(a)));

或者使用emplace()函数:

my_map.emplace(0, std::ref(a));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接