anonymous
anonymous

Reputation: 471

Why couldnt we have moving iterators?

C++11 introduced a "move" algorithm that behaves like the "copy" algorithm except that it... moves the data instead of copying it. I'm wondering why the commitee didnt update the copy algorithm to use forward instead (or probably in addition to that).

A vector provides an iterator of T& A const vector provides an iterator of const T& Is there a reason why a vector&& couldnt provide an iterator of T&&? That would allow to move elements from say a list to a vector by using vector's constructor...

Is that a bad idea?

Upvotes: 7

Views: 1158

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218700

See std::move_iterator.

#include <list>
#include <vector>

#include <iostream>

struct A
{
    A() = default;
    A(A&&) {std::cout << "move\n";}
    A(const A&) = default;
};

int main()
{
    std::list<A> l = {A(), A(), A()};
    std::vector<A> v(std::make_move_iterator(l.begin()),
                     std::make_move_iterator(l.end()));
}

move
move
move

Upvotes: 10

Kerrek SB
Kerrek SB

Reputation: 476950

We have those already. Use std::make_move_iterator to create a move iterator.

Upvotes: 16

Related Questions