将 boost::iterator_range 分配给奇异范围
我使用 Boost.Range 传递一些数据和该数据的容器类。数据在不同的线程中加载,在某些情况下可能尚未准备好。在这种情况下,容器使用默认的 iterator_range 进行初始化,因此包含单个迭代器。我正在对数据容器进行赋值和复制(因此是 iterator_ranges)。但是,iterator_range 复制构造函数调用 begin() 和 end(),当原始值是单数时,它们将断言。因此,不可能复制空数据容器。
有什么办法可以避免这个限制吗?
为什么要实施此限制?以下工作正常,范围不应该表现类似吗?
typedef std::vector<int>::iterator iterator;
iterator it; // Singular
iterator it2 = it; // Works
boost::iterator_range<iterator> range; // Singular
boost::iterator_range<iterator> range2 = range; // Asserts in debug, but why?
I'm using Boost.Range to pass around some data and a container class for this data. The data is loaded in a different thread and may in some cases not be ready yet. In this case the container is initialized with the default iterator_range, hence containing singular iterators. I'm doing assignments and copying of the data containers (hence the iterator_ranges). However, the iterator_range copy constructor calls begin() and end() which will assert when the original is singular. Therefor, it is not possible to copy an empty data container.
Is there any way to avoid this limitation?
Why is this limitation been implemented? The following works just fine, shouldn't ranges behave similarly?
typedef std::vector<int>::iterator iterator;
iterator it; // Singular
iterator it2 = it; // Works
boost::iterator_range<iterator> range; // Singular
boost::iterator_range<iterator> range2 = range; // Asserts in debug, but why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果“有效”是指“它不会因我当前的编译器版本和调用选项而崩溃”,那么是的,分配单个迭代器可能“有效”。
实际上,代码
会导致未定义的行为,因此您可以根据编译器的突发奇想来决定可能发生的情况。
C++ 标准对此有这样的说法([lib.iterator.requirements]/5 节):
因此,最终范围的工作方式与单个迭代器类似。它只是无法按照您想要的方式工作。
我认为最好的方法是在数据尚未准备好时使用空范围(使用非奇异迭代器显式构造),而不是使用奇异范围。
If by "works", you mean "it does not blow up with my current compiler version and invocation options", then yes, assigning a singular iterator might "work".
Actually, the code
results in undefined behaviour, so you are up to the whims of your compiler for what may happen.
The C++ standard has this to say about it (section [lib.iterator.requirements]/5):
So, in the end ranges do work similar to single iterators. It just doesn't work the way you would like.
I think the best way is to use an empty range (explicitly constructed with to non-singular iterators) when the data is not yet ready, instead of a singular range.