Where is my move assignment?!

Hi, I was having this exercise where I had to implement simple

default constructor
constructor
copy constructor
copy assignment
move constructor
move assignment
destructor

for a simple class and in those function bodies just cout << "Where I'm at\n";

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace std;

class X {
	int val{0};
public:
	X(int x) : val{ x } { cout << "X constructor\n"; }
	X() : val{ 0 } { cout << "X default constructor\n"; };

	X(const X& c) : val{ c.val } { cout << "copy constructor\n"; }
	X& operator=(const X& c) { val = c.val; return *this; cout << "copy assignment\n"; }

	X(X&& a) : val{ a.val } { cout << "\tmove constructor\n"; }
	X& operator=(X&& a) { val = a.val; return *this; cout << "\tmove assignment\n"; }

	~X() { cout << "~Destructor()\n"; }

};

int main() {

	X x1{10};   //constructor
	X x2;       //default constructor

	x2 = x1;    //nothing???

}


Why x2 = x1; line does produce "copy assignment" output?
move assignment works for temporaries, i.e. variables which are not bound to names or pointers, like X(). Also you should include <algorithm> and use val{std::move(a.val)} in you move constructor to ensure you actually move it.
1
2
3
4
5
6
	X& operator=(const X& c)
	{
		val = c.val;
		return *this;
		cout << "copy assignment\n"; //¿you wonder why you don't see this?
	}
:D All right, yea my mistake as always. Thank you guys :)
TheHardew wrote:
Also you should include <algorithm> and use val{std::move(a.val)} in you move constructor to ensure you actually move it.

The header you should include is <utility>. There is a std::move in <algortihm> too but it's not the one that is used here.
Tnx for this good update man! Checked out both of them.
Topic archived. No new replies allowed.