Forwarding Arguments with std::forward
In C 0x, std::forward is used to forward arguments to another function call. This is advantageous when you want to avoid having to explicitly copy or move the arguments.
The usage of std::forward involves using the &&& notation in the function parameters. This notation allows you to accept both lvalue and rvalue references as arguments.
In the example given:
<code class="cpp">template<class T> void foo(T&&& arg) { bar(std::forward<T>(arg)); }</code>
The std::forward
However, you should not use std::forward in all cases. It is only necessary when you need to preserve the reference type of the argument. For example, if you have a function that does not take rvalue references, you should not use std::forward.
In the following example:
<code class="cpp">template<int val, typename... Params> void doSomething(Params... args) { doSomethingElse<val, Params...>(args...); }</code>
You do not need to use std::forward because the doSomethingElse function can take lvalue or rvalue references.
However, if you have a function that does take rvalue references, you should use std::forward to ensure that the arguments are forwarded as rvalue references. For example:
<code class="cpp">template<int val, typename... Params> void doSomething(Params&&... args) { doSomethingElse<val, Params...>(std::forward<Params>(args)...); }</code>
In this example, std::forward is used to ensure that the arguments are forwarded as rvalue references, even if they are initially lvalue references.
Finally, you should not forward an argument multiple times. This can lead to undefined behavior. For example, the following code is incorrect:
<code class="cpp">template<int val, typename... Params> void doSomething(Params&&... args) { doSomethingElse<val, Params...>(std::forward<Params>(args)...); doSomethingWeird<val, Params...>(std::forward<Params>(args)...); }</code>
In this example, the arguments are forwarded twice, which can lead to undefined behavior.
The above is the detailed content of ## When Should I Use std::forward in C ?. For more information, please follow other related articles on the PHP Chinese website!