[英]Why does ranges-v3 not move elements even the iterator is std::move_iterator?
#include <range/v3/all.hpp>
#include <vector>
#include <string>
#include <deque>
using namespace std::literals;
int main()
{
auto src = std::vector{"123"s, "456"s, "789"s};
auto movable_rng = ranges::subrange(
std::make_move_iterator(src.begin()),
std::make_move_iterator(src.end()));
auto dst = ranges::to<std::deque<std::string>>(movable_rng);
for (auto e : src)
{
std::cout << e << std::endl;
}
for (auto e : dst)
{
std::cout << e << std::endl;
}
}
用 clang 10 和 libc++ 编译,output 是:
123
456
789
123
456
789
正如我所料,结果应该是:
""
""
""
123
456
789
为什么即使迭代器是std::move_iterator
也不移动元素?
=======更新=======
我的范围版本是: range-v3-0.10.0
。 Even I replace std::string
with std::vector<char>
, the problem is still reproducible on my linux docker, both gcc and clang produce the same result.
但是,在godbolt.org上可以使用相同的代码,但我不确定godbold.org上的范围版本是3.0.10
。
cppreference上的示例代码如下:
std::string str1;
std::string str2 { "alpha" };
...
str1 = std::move(str2);
std::cout << std::quoted(str1) << ' ' // "alpha"
<< std::quoted(str2) << '\n'; // "" or "alpha" (unspecified)
可能由于小的字符串优化,没有要求移动的字符串为空。 允许在移动后保持不变。 唯一的要求是它仍然在有效的 state 中。
从 object 移出后,它会保留在有效但未定义的 state 中。 由于您的字符串都很小,因此很有可能所有字符都存储在 object 中,而不是堆中(SSO)。 这使得在“移动”之后将被移动的字符串归零的效率较低(稍微)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.