c++ - 构造一个持有引用的 unordered_map 是否合法?

标签 c++ reference containers unordered-map

一般来说,STL 容器不能容纳非CopyAssignable 类型,例如引用。如果我以不应该发生复制的方式构建容器,那么代码是否有效。它使用 std=c++11c++14 与某些版本的 gcc-7.2 编译,但以下是否有效,或者我可以预期它会中断图书馆升级?在这种情况下我应该使用 reference_wrapper 吗?

#include <unordered_map>

struct S {};

void use (S&) {}

void test() {
    S s1, s2;
    const std::unordered_map<int, S&> m{{0, s1}, {1, s2}};
    use(m.at(0));
}

编辑 我确实需要引用标准。如果编译器/标准库的符合标准的更新可以破坏代码,那么对我来说也是不够的。所以给出的答案是"unordered_map with reference as value"对我来说还不够。

最佳答案

我想我自己找到了这个特定用例的答案:

C++11条款 23.5.4.3 中关于 unordered_map 元素访问的标准特别省略了列出对 mapped_type 的任何要求,即 S&,而对于 operator[] 它必须是 DefaultConstructible

mapped_type& at(const key_type& k);
const mapped_type& at(const key_type& k) const;

Returns: A reference to x.second, where x is the (unique) element whose key is equivalent to k.

Throws: An exception object of type out_of_range if no such element is present.

C++17在 26.5.4.3 和 26.5.4.4 中也间接说明了这种效果。

因此,上述代码应该适用于任何标准实现。

但是,正如评论中所指出的那样,在构建或应用任何需要构建或分配容器的 value_typemapped_type 将不起作用。

关于c++ - 构造一个持有引用的 unordered_map 是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46770274/

相关文章:

c++ - boost::scoped_ptr 是否违反逻辑常量准则

c++ - 在容器上的循环中同时访问更多元素的 STL 方法

java - 如何发送列表的值而不是引用(其中列表是 map 的值)?

NGINX-代理 : Running multiple ports tied to different virtual hosts on one container

Docker 容器 - 选项 "--detach-keys Override the key sequence for detaching a container"是什么意思?

c++ - `Counter::metaObject() const'的多重定义

c++ - 在 C++ 中使用指针更改字符串值

c++ - 为什么我应该在 unordered_map 参数前添加 '&'?

c# - 为什么我们不能将对象直接分配给返回相同类型的方法?

angular - 前端无法到达单独的 docker 容器中的后端端口