将迭代器取消引用到临时范围时出现非指针操作数错误 [英] Non-pointer-operand error when dereferencing an iterator into a temporary range

查看:392
本文介绍了将迭代器取消引用到临时范围时出现非指针操作数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用

auto empty_line = [](auto& str){ return str.size() == 0; };

我们可以这样做:

auto line_range_with_first_non_empty = 
                ranges::view::drop_while(ranges::getlines(std::cin),empty_line);
auto input1 = std::stoi(*line_range_with_first_non_empty.begin());

我们也可以这样做:

auto line_range2 = ranges::getlines(std::cin);
auto iter2 = ranges::find_if_not(line_range2,empty_line);
auto input2 = std::stoi(*iter2);

不幸的是,当我尝试将以上版本缩短为:

Unfortunately, when I try to shorten version above into:

auto iter3 = ranges::find_if_not(ranges::getlines(std::cin),empty_line);
// auto input3 = std::stoi(*iter3);

我得到一个错误:

<source>:22:29: error: indirection requires pointer operand ('ranges::v3::dangling<ranges::v3::_basic_iterator_::basic_iterator<ranges::v3::getlines_range::cursor> >' invalid)
    auto input3 = std::stoi(*iter3);
                            ^~~~~~

我认为是因为存在无限范围,但我错了.

I thought it's because of that infinite range but I was wrong.

auto sin = std::istringstream{"\n\n\nmy line\n"};
auto iter4 = ranges::find_if_not(ranges::getlines(sin),empty_line);
// Error when deref.
// auto input4 = std::stoi(*iter4);

这会产生相同的错误.

<source>:27:29: error: indirection requires pointer operand ('ranges::v3::dangling<ranges::v3::_basic_iterator_::basic_iterator<ranges::v3::getlines_range::cursor> >' invalid)
    auto input4 = std::stoi(*iter4);
                        ^~~~~~

ranges::find_if将范围作为右值时,为什么不能取消引用?

Why can't I dereference when ranges::find_if takes a range as rvalue?

ranges::getlines是否返回范围?如果是这样,范围应该拥有东西吗?

Does ranges::getlines return a range? If so, are ranges supposed to own things?

godbolt.org/g/Yo6tKa

推荐答案

如果传递给算法的范围是临时的,并且该算法返回迭代器,则将该迭代器包装在dangling包装器中,以防止您执行此操作任何不安全的东西.任务完成. :-)

If the range passed to an algorithm is a temporary, and the algorithm returns an iterator, the iterator is wrapped in a dangling wrapper to keep you from doing anything unsafe. Mission accomplished. :-)

这篇关于将迭代器取消引用到临时范围时出现非指针操作数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆