[Help rvalue]

Aug 27, 2014 at 3:10am
Somebody help me!!!

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
  using namespace std;

class Test {
	public:
		Test(){
			cout<<"Default constructor"<<endl;
		}
		Test(const Test& t) {			
			cout<<"Copy constructor"<<endl;
		}
		Test(Test&& t) {
			cout<<"Move constructor"<<endl;
		}
		Test& operator = (const Test& t) {
			cout<<"Copy assignment"<<endl;
		}
		Test& operator = (Test&& t) {
			cout<<"Move assignment"<<endl;
		}
		
};

Test getTest() {
	return Test();
}

int main(int argc, char** args) {
	Test t (getTest()); // this line (1)
}


I don't really understand if the return value of getTest() in the line (1) is lvalue or rvalue.
And when I compile and run the program, it seem none of those constructor is used for t.
Somebody plz explain to me. Thank you.
p/s: when i add this line:
 
getTest() = Test(); // No error or warning 

in the main function, no problem.
But,
1
2
3
4
5
6
7
// define a function that returns 1
int getInt() { return 1; }

// in main function
//...
getInt() = 2; // error because the return value of getInt() is rvalue,
//so it can not be in the left hand side of assignment 

So i'm confused about rvalue and lvalue here.
Last edited on Aug 27, 2014 at 3:22am
Aug 27, 2014 at 3:28am
Look up 'copy elision'. Your compiler is smart and elides the move/copy.
Last edited on Aug 27, 2014 at 3:28am
Aug 27, 2014 at 8:30am
I don't really understand if the return value of getTest() in the line (1) is lvalue or rvalue.
rvalue

The point of move is that the rvalue can [potentially] be modified.
In case of getTest() = Test();: Not the returned value but the assigned value could be modified, hence that assignment is allowed.

line (1) is perfectly valid since the result of getTest() is used as a rvalue.
Aug 27, 2014 at 8:38am
Thank you all!

line (1) is perfectly valid since the result of getTest() is used as a rvalue

If so, the result of program must print "Move constructor" when call the move constructor. But in fact, it doesn't. So I don't know which constructor is used.
Aug 27, 2014 at 10:55am
The effect of line (1) is what LB said. The compiler detects that only the default constructor is involved
Aug 28, 2014 at 2:12am
The effect of line (1) is what LB said.

Thank you! :)
Topic archived. No new replies allowed.