简体   繁体   中英

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;
    }
}

Compiled with clang 10 with libc++ and the output is:

123
456
789
123
456
789

As I expected, the result should be:

""
""
""
123
456
789

Why does ranges-v3 not move elements even the iterator is std::move_iterator ?

======= Update =======

My ranges version is: 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.

However, the same code is ok on godbolt.org , but I am not sure the ranges' version of ranges on godbold.org is 3.0.10 .

The example code on cppreference has this:

std::string str1;
std::string str2 { "alpha" };
...
str1 = std::move(str2);
std::cout << std::quoted(str1) << ' ' // "alpha"
          << std::quoted(str2) << '\n'; // "" or "alpha" (unspecified)

Probably due to small string optimizations, there's no requirement that the moved-from string is empty. It's allowed to be left unchanged after a move. The only requirement is that it's still in a valid state.

Moving from an object leaves it in a valid, but not defined state. It's perfectly possible that, since your strings are all small, the characters are all stored inside the object and not on the heap (SSO). This makes it less efficient (slightly) to zero the moved-from string after "moving" from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM