一般来说,STL 容器不能容纳非CopyAssignable
类型,例如引用。如果我以不应该发生复制的方式构建容器,那么代码是否有效。它使用 std=c++11
和 c++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
, wherex
is the (unique) element whose key is equivalent tok
.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_type
或 mapped_type
将不起作用。
关于c++ - 构造一个持有引用的 unordered_map 是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46770274/