Difference between std::move and std::forward

In really simple terms, std::move returns an argument as an rvalue reference while std::forward returns either an lvalue reference or an rvalue reference based on how the argument was passed in to the current function. While this is fairly obvious once you get the hang of it, it can be quite tricky to grasp earlier on. The easiest way to see how they work differently is to try some code such as the following:

void Show(int&&)
{
	cout << "int&& called" << endl;
}

void Show(int&)
{
	cout << "int& called" << endl;
}

template<typename T> void Foo(T&& x)
{
	cout << "straight: ";
	Show(x);

	cout << "move: ";
	Show(move(x));
	
	cout << "forward: ";
	Show(forward<T>(x));
	
	cout << endl;
}

int _tmain(void)
{
	Foo(10);

	int x=10;
	Foo(x);
	return 0;
}

The output of the above code is:

straight: int& called
move: int&& called
forward: int&& called

straight: int& called
move: int&& called
forward: int& called

When Foo is called with an rvalue, T&& is deduced as int&&. But the variable itself is an lvalue within that function. So the straight call calls the Show(int&) overload – no surprises there. Both the move-call and the forward-call calls Show(int&&) as expected. In the 2nd case, Foo is called with an lvalue, and again the straight call will go to Show(int&) while the move-call will go to Show(int&&). Now here’s where forward comes in handy, it will go to Show(int&) because that’s what T has been deduced to in this instance of the function call (perfect forwarding). If you are wondering why, the collapsing rule for T&& collapses it to T& during template argument type deduction.

One thought on “Difference between std::move and std::forward

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s