下面的做法是not编译:
#include <iostream>
int main()
{
int a{},b{},c{},d{};
for (auto& s : {a, b, c, d}) {
s = 1;
}
std::cout << a << std::endl;
return 0;
}
在 Godbolt 上尝试一下 https://godbolt.org/z/_5Izir
编译器错误是:error: assignment of read-only reference 's'
现在,在我的实际情况中,列表由类的成员变量组成。
现在,这不起作用,因为表达式变成了initializer_list<int>
实际上复制了 a、b、c 和 d - 因此也不允许修改。
我的问题有两个:
不允许以这种方式编写基于范围的 for 循环背后是否有任何动机? 例如。也许裸括号表达式可能存在特殊情况。
什么是句法整齐修复这种类型循环的方法?
沿着这条线的东西将是首选:
for (auto& s : something(a, b, c, d)) {
s = 1;
}
我不认为指针间接是一个好的解决方案(即{&a, &b, &c, &d}
) - 当迭代器被取消引用时,任何解决方案都应该直接给出元素引用.