Why does a range-based for statement take the range by auto&&?

こ雲淡風輕ζ 提交于 2019-11-30 11:25:42

Wouldn't auto& suffice?

No, it wouldn't. It wouldn't allow the use of an r-value expression that computes a range. auto&& is used because it can bind to an l-value expression or an r-value expression. So you don't need to stick the range into a variable to make it work.

Or, to put it another way, this wouldn't be possible:

for(const auto &v : std::vector<int>{1, 43, 5, 2, 4})
{
}

Wouldn't const auto& suffice?

No, it wouldn't. A const std::vector will only ever return const_iterators to its contents. If you want to do a non-const traversal over the contents, that won't help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!