Why is Copy Constor called with Move Constructor?

This problem seems strange, but I checked several compilers. In my code I have Move Constructorand copy constructorhow

class A {
    int val;
public:
    A(int var) : val(var)  {
    }
    A( A && a1) {
        cout<<"M Value -> "<<a1.val<<endl;
        cout<<"Move Cons..."<<endl;
     }
    A(const A & a1) {
        cout<<"Copy Cons.."<<endl;
        cout<<"Value -> "<<a1.val<<endl;
    }
};

If I write my function mainas

int main()
{
    vector<A> v1;
    A a2(200);
    v1.push_back(move(a2));              
}

Output signal

M Value -> 200
Move Cons...

Expected, but if I change my function mainas

int main()
{
    vector<A> v1;
    A a2(200);
    v1.push_back(A(100));
    v1.push_back(move(a2));

}

I get the following output

M Value -> 100
Move Cons...
M Value -> 200
Move Cons...
Copy Cons..   // unexpected
Value -> 0    // unexpected

Can someone help me figure out where and how this one copy constructoris being called ... this too with meaning0

thank

+4
source share
1 answer

The reasons have already been addressed in the comments. I will try to illustrate what is happening.

Steps:

vector<A> v1;

  • Vector selection. It internally reserves space for one element.

v1.push_back(A(100));

  1. Build and move A(100)inside the vector.

v1.push_back(move(a2));

  1. , , . , std::vector .
  2. a2 v1.
  3. ( ) v1 v1.

:

1) ## v1[undef ] #########################
2) ## v1[A(100)] #########################
3) ##   [A(100)] ### v1[undef,  undef ] ##
4) ##   [A(100)] ### v1[undef,  A(200)] ##
5) ##   [A(100)] ### v1[A(100), A(200)] ##

:

0, , val undefined. 100.

noexcept, .

v1.emplace_back(100) v1.push_back(A(100)), .

+1

Source: https://habr.com/ru/post/1691357/


All Articles