Help with move constructor

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
29
30
31
32
33
34
35
36
#include <iostream>

class T {
	int x;
public:
	T() :x(-1) {}
	T(int a) :x(a) {}
	T(const T& a) :x(a.x) { }
	T& operator=(const T& a) {
		x = a.x;
		return *this;
	}
	T(T&& a) :x(a.x) {
                 std::cout << "move constructor\n";
                 a.x = -1;
        }
	T& operator=(T&& a) {
                x = a.x;
		std::cout << "move assignment\n";
		a.x = -1;
		return *this;
	}
};

T g() {
	T t{ 50 };
	return t;
}

int main() {
	T t2; // default constructor
	t2 = g(); // move constructor : ???
	          // move assignment  : OK

	system("PAUSE");
}


When executed:
move constructor // why move constructor is called
move assignment
Press any key to continue . . .
Last edited on
why move constructor is called

Probably to construct the return value from t. Try turning on more optimizations and see if it makes a difference. When I run your program the only output that I see is "move assignment val:50".
Yes that's what is happening i guess; I think the compiler is converting the return value to T like this:
t2 = T{ g() }
I just compiled this program in cpp.sh and it gave me the same result as you.
turning on optimizations did not make any differences; I am using visual studio 2017
Last edited on
Topic archived. No new replies allowed.