1

Consider this code:

#include <iostream>
using namespace std;

class A
{
int x;
public:
A () {x=5;}
A (const A & a) {x=a.x;}
A (A && a) {x=move(a.x);}
A & operator= (const A & a) {x=a.x;}
A & operator = (A && a) {x=move(a.x);}

void func () {A a; *this=move(a);}

}; 

int main () {A a; a.func();}

A::func() creates an A object, then *this is assigned to A using move operator=. What are the differences between move operator= and copy operator= in that assignment? Is it more efficient to use move assignment operator explicitly (using move) rather than the copy operator when the object I want to copy will expire at the end of the function? If I use the move assignment operator does a still exist, after the assignment?

Tony
  • 35
  • 1
  • 4
  • It isn't a great example because moving an `int` just copies it, making them effectively the same operation. – chris Sep 12 '15 at 20:09
  • Also, you use move assignment in the move constructor, instead fo moving directly. You're moving an `int` so it doesn't matter. But it could matter for other types and it seems odd in any case. – juanchopanza Sep 12 '15 at 21:22

2 Answers2

2

Your question "Is it more efficient to use move assignment" is kind of backwards. You use move assignment when it is more efficient.

If you think you can implement move assignment "better" that copy assignment, you can add another operator.

If, like in your example, you find that it is hard to optimize the operation of copying an int, you don't bother with moving.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • I have a similar situation but concerning much more heavier objects. I tried to use the move assignment operator because I thought that moving, rather than releasing and then creating new memory (which is what my copy assignment operator does), would be more efficient because the object I move (like in the previous code) will expire ad the end of the function. I wonder if my thoughts are right or if moving might create problems. – Tony Sep 12 '15 at 20:45
0

If copy operations are expensive (suppose you have heavy members) - it make sense to use move(for example, you can copy just pointers on heavy members).

Move Constructor The purpose of a move constructor is to steal as many resources as it can from the original object, as fast as possible, because the original does not need to have a meaningful value any more, because it is going to be destroyed (or sometimes assigned to) in a moment anyway.

malchemist
  • 434
  • 2
  • 13