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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With