dimanche 23 octobre 2016

C++ - passing rvalues to function by values

I am just reading "Effective Modern C++" by Scott Meyers and I am testing such a code:

class A
{
public:
    A(int _a) : a(_a)
    {   
        printf("Constructor A %d\n",a);
    }
    A(A&& tmp) noexcept
    {
        printf("MOVE constructor\n");
        a=std::move(tmp.a);
    }
    A(const A & tmp)
    {
        printf("COPY constructor\n");
        a= tmp.a;
    }
 private:
    int a;
 };
std::vector<A> v;
void fun(A temp)
{   
    v.push_back(std::move(temp));
}

void fun2(A&& temp)
{
    v.push_back(std::move(temp));
}

int main()
{
    A x(3);
    fun(x);
    printf("\n");
    fun(A(5));
    printf("\n");
    fun2(A(6));
}

Output which I can see is

Constructor A 3
COPY constructor
MOVE constructor

Constructor A 5
MOVE constructor
MOVE constructor

Constructor A 6
MOVE constructor
MOVE constructor
MOVE constructor

I have doubts about second call of fun. Both move constructors are used during

v.push_back(std::move(temp));

How it works that no move constructor is used to create param of fun? In first case copy constructor is called so I assume that during second call of fun move constructor should be called. My next question is how it works that in first call of fun

v.push_back(std::move(temp));

calls only one move constructor and second call of fun calls 2 move constructor. The same line calls move constructor 3 times during call fun2. Why?

Thank you in advance for your answer

Aucun commentaire:

Enregistrer un commentaire