Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::forward<T> vs static_cast<T>

From what I understand, std::forward<T>(x) is equivalent to static_cast<T&&>(x).

But from what I saw, static_cast<T>(x) seems to do the same thing, as can be seen in the following code

My question is therefore why std::forward<T> is implemented as static_cast<T&&>(x), and not static_cast<T>(x), if both have the same effect?

like image 947
Mikrosaft Avatar asked Sep 27 '15 09:09

Mikrosaft


2 Answers

Because perfect forwarding allows to pass both r-value references and l-value references. This is done via reference collapsing:

T = int    --> T&& = int&&
T = int&   --> T&& = int& && = int&
T = int&&  --> T&& = int&& && = int&&

In your example with static_cast<T> you're simply losing r-value references. It works fine for primitive types (because passing int is usually copying a CPU register value), but awful for complex types because it leads to creating temporary object through copy ctors.

like image 169
myaut Avatar answered Sep 20 '22 08:09

myaut


If T&& is an rvalue reference, then T is a value, then static_cast<T> makes a copy not a rvalue reference.

That copy will bind to rvalue references (just like the reference), but copy/move ctors could be needlessly called, and it is not a candidate for elision.

static_cast<T&&> will meanwhile just cast to an rvalue reference.

They are otherwise identical.

like image 45
Yakk - Adam Nevraumont Avatar answered Sep 23 '22 08:09

Yakk - Adam Nevraumont