If I accept a value by copy/move and then perform a move on it, it seems to copy LValues and move RValues.
Will this code perform correctly and efficiently for both cases?
Is it a reasonable alternative to creating RValue and LValue overloads for useA2()?
struct A
{
int *buff;
A() { cout << "A::constructor\n"; buff = new int[1000]; } //expensive
A(const A& a) { cout << "A::copy constructor\n"; buff = new int[1000]; memcpy(buff, a.buff, 1000); }
A(A&& a) { cout << "A::move constructor\n"; buff = a.buff; a.buff = nullptr; }
~A() { cout << "A::destructor\n"; delete buff; }
};
A getA()
{
A temp; // without temp, compiler can perform copy elision, skipping copy/move constructors
return temp;
}
void useA2(A a)
{
A a1 = std::move(a);
}
void demo()
{
A a1;
//useA2(getA()); // performs 2 moves
useA2(a1); // performs a copy to the input param, then moves the copy
}
Aucun commentaire:
Enregistrer un commentaire