【发布时间】:2018-10-21 11:02:13
【问题描述】:
在 std::unordered_map 上运行基于范围的 for 循环时,循环变量的类型似乎不使用引用类型:
std::unordered_map<int, int> map = { {0, 1}, {1, 2}, {2, 3} };
for(auto&[l, r] : map)
static_assert(std::is_same_v<decltype(r), int&>);
MSVC 2017、gcc 8.2 和 clang 7.0.0 在这里都报告了一个失败的断言。将此反对 std::vector,其中断言不会失败,正如人们所期望的那样:
std::vector<int> vec = { 1, 2, 3 };
for(auto& r : vec)
static_assert(std::is_same_v<decltype(r), int&>);
但是,在 MSVC 2017 和 gcc 8.2 上,修改局部变量 r 的循环都会产生明显的副作用:
#include <iostream>
#include <type_traits>
#include <unordered_map>
#include <vector>
int main() {
std::unordered_map<int, int> a = { {0, 1}, {1, 2}, {2, 3} };
for(auto[l, r] : a)
std::cout << l << "; " << r << std::endl;
for(auto&[l, r] : a) {
static_assert(std::is_same_v<decltype(r), int>);
r++;
}
std::cout << "Increment:" << std::endl;
for(auto[l, r] : a)
std::cout << l << "; " << r << std::endl;
}
这个程序例如会打印(忽略顺序):
0; 1
1; 2
2; 3
Increment:
0; 2
1; 3
2; 4
我错过了什么? 尽管局部变量不是引用类型,但这如何改变地图中的值? 或者更恰当地说,为什么 std::is_same 看不到正确的类型,因为很明显它是一个引用类型? 或者我是否遗漏了一些未定义的行为?
请注意,我确实在不使用结构化绑定的情况下重现了相同的问题,因此我将漂亮的代码保留在这里。 See here for an example
【问题讨论】:
-
罪魁祸首是
decltype:"If the argument is an unparenthesized id-expression naming a structured binding, then decltype yields the referenced type"。但我承认我不知道这样做的理由是什么。 -
@HolyBlackCat 使 C++ 更加混乱和不一致。似乎是我们在过去几年添加的所有内容的基本原理。
标签: c++ language-lawyer c++17 unordered-map structured-bindings