operator= called instead of move-constructor?

Hi,

std::swap always seem to involve only one move operation and two operator=. Why that? I would have expected two moves and one operator=.

please consider the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct S
{
	S() { cout << "default" << endl; }
	S(const S&) { cout << "copy" << endl; }
	S(const S&&) { cout << "move" << endl; }
	S& operator=(const S&) { cout << "equals" << endl; return *this; }
};

void my_swap(S& s1, S& s2)
{
	S tmp(std::move(s1));
	s1 = std::move(s2);
	s2 = std::move(tmp);
}

int main()
{
	S s1,s2;
	cout << "---" << endl;
	std::swap(s1,s2);
	cout << "---" << endl;
	my_swap(s1,s2);
}
default
default
---
move
equals
equals
---
move
equals
equals


The function my_swap is an attemp to get my 2xmove + 1xequal, but to no avail. Why can't the last std::move in line 13 use the move-constructor? "tmp" is non-const and clearly not used afterwards...

Or is it just that the compiler is not good enough yet?

Does anyone has a GCC4.3+ at hand? (The one I have here is too old :-( )

Ciao, Imi.
Last edited on
never mind. Found the answer. :-(

"For safety reasons a named variable will never be considered to be an rvalue even if it's declared as such"

Ciao, Imi.
Actually, it's even stranger. I guess I don't understand rvalue references at all. I have to read everything carefully again... so please people, go on.. there is nothing to see... ;-)


Because:

1
2
3
4
5
6
7
8
9
10
11
12
13
void my_swap(S& s1, S& s2)
{
	S&& tmp(std::move(s1));
	s1 = std::move(s2);
	s2 = std::move(tmp);
}

int main()
{
	S s1,s2;
	cout << "---" << endl;
	my_swap(s1,s2);
}
default
default
---
equals
equals


2x equals and no move???

Ciao, Imi.
Last edited on
Topic archived. No new replies allowed.