#include <iostream>
#include <utility>
#include <vector>

int i = 0;
struct A
{
    A() : j( ++i )
    {
        std::cout<<"constructor "<<j<<std::endl;
    }
    A( const A & c) : j(c.j)
    {
        std::cout<<"copy "<<j<<std::endl;
    }
    A( const A && c) : j(c.j)
    {
        std::cout<<"move "<<j<<std::endl;
    }
    ~A()
    {
        std::cout<<"destructor "<<j<<std::endl;
    }

    int j;
};

typedef std::vector< A > vec;

void foo( vec & v )
{
    v.push_back( std::move( A() ) );
}

int main()
{
    vec v;

    foo( v );
    foo( v );
}

The example above produces next output :

constructor 1
move 1
destructor 1
constructor 2
move 2
move 1
destructor 1
destructor 2
destructor 1
destructor 2

Questions :

  1. Why is the 1st destructor executed (but it isn't executed for the 2nd object)?
  2. Why is move of the 2nd object, executed before the move of the 1st object?
  3. Why are at the end two destructors for each object executed?

PS I just checked, and the objects are indeed placed as expected (the 1st goes to the position 0 in the vector, and the 2nd goes to the position 1 in the vector)

PPS If it matters, I am using gcc 4.3, and I compile the program like this :

g++ n1.cpp -Wall -Wextra -pedantic -ansi -std=c++0x -O3
Edit
Report