0

I am trying to move elements in a vector, here is a simplified example

#include <iostream>
#include <vector>

struct A
{
    A(size_t i) noexcept : i(i) 
    { std::cout << "A-" << i << std::endl; }

    A(A const& a) noexcept : i(a.i) 
    { std::cout << "A copy" << std::endl; }

    void operator=(A const& a) noexcept
    {
        i = std::move(a.i);
        std::cout << "A op=" << std::endl;
    }

    A(A&& a) noexcept : i(std::move(a.i)) 
    { std::cout << "A move" << std::endl; }

    ~A() noexcept { }

    int i;
};

int main()
{
    // A a0(0);
    // A a1 = std::move(a0);

    std::vector<A> v;
    v.reserve(2);
    v.emplace_back( 0 );
    v.emplace_back( 1 );
    v.emplace_back( 2 );
    v[0] = std::move( v[2] );
    v[2] = std::move( A(3) );

    return 0;
}

The vector calls move when resizing; i dont understand why v[0] = std::move( v[2] ); doesn't call the move function?

My output when building with gcc version 4.7.2 is

A-0
A-1
A-2
A move
A move
A op=
A-3
A op=
Jon
  • 1,785
  • 2
  • 19
  • 33

1 Answers1

2

You defined a move constructor, but you have no move assignment defined.

A& operator = (A&&);

And your regular assignment operator should return a reference:

A& operator=(A const& a) 
{
    std::cout << "A op=" << std::endl;
    return *this;
}
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
  • Thanks. I can accept your answer 7 minutes from now. I should have known that std::move was returning an `A&&` and I had no `operator=(A&&)` function defined. – Jon Apr 01 '13 at 03:16