C中的完美转发是一种允许将参数从一个函数传递到另一个函数的技术,同时保持其原始价值类别(LVALUE或RVALUE)和类型。当需要以保留原始呼叫的效率和语义的方式,需要将参数转发到其他函数时,这一点特别有用。
完美的转发作品通过将参考折叠和std::forward
结合起来。以下是其运作方式:
T& &&
)的RVALUE引用倒入LVALUE参考( T&
),以及任何其他组合( T&& &&
华氏度T& &
)崩溃到了所需参考的类型。T&&
(通常使用auto&&
或模板参数)实现的。std::forward
实用程序在函数中使用将参数转发到另一个函数,并保留其价值类别。当您使用std::forward<t>(arg)</t>
时,如果T
是lvalue参考,则会将arg
给T
,或者T&&
如果T
是rvalue参考。这是一个简单的示例,展示了完美的转发:
<code class="cpp">template<typename t> void wrapper(T&amp;& arg) { // Forward 'arg' to another function, preserving its value category anotherFunction(std::forward<t>(arg)); } void anotherFunction(int& arg) { /* lvalue overload */ } void anotherFunction(int&& arg) { /* rvalue overload */ } int main() { int x = 5; wrapper(x); // Calls anotherFunction(int&) because x is an lvalue wrapper(5); // Calls anotherFunction(int&&) because 5 is an rvalue return 0; }</t></typename></code>
在此示例中, wrapper
使用完美的转发将arg
传递给anotherFunction
,从而可以根据原始参数的值类别重载anotherFunction
。
在C中使用完美转发的好处包括:
完美的转发可以通过多种方式显着提高C中C功能的效率:
这是一个示例,说明完美转发如何提高效率:
<code class="cpp">template<typename t> void efficientWrapper(T&amp;& arg) { std::vector<int> v(std::forward<t>(arg)); // Efficiently constructs v from arg } int main() { std::vector<int> source = {1, 2, 3}; efficientWrapper(std::move(source)); // Moves the contents of source into v return 0; }</int></t></int></typename></code>
在此示例中, efficientWrapper
使用完美的转发来从arg
中有效地构造v
如果arg
是rvalue(例如在main
函数中),则使用移动语义来避免不必要的复制。
在C中实施完美的转发时,有几个常见的陷阱要注意并避免:
std::forward
: std::forward
只能在最初取转引用的功能中使用。在此上下文之外使用它可能会导致不正确的行为。例如,将转发参考存储在成员变量中,然后将其转发为以后会引起问题。T&amp; &&
倒入T&
,而T&& &&
倒入T&&
。这是一个常见陷阱以及如何避免这种情况的一个例子:
<code class="cpp">// Incorrect use of std::forward class IncorrectUsage { template<typename t> void incorrectForward(T&amp;& arg) { store = std::forward<t>(arg); // Incorrect: don't use std::forward here } std::string store; }; // Correct use of std::forward class CorrectUsage { template<typename t> void correctForward(T&amp;& arg) { store = std::forward<t>(arg); // Correct: use std::forward immediately } std::string store; };</t></typename></t></typename></code>
在IncorrectUsage
类中, std::forward
用于存储的成员变量,这可能导致不正确的行为。在CorrectUsage
类别中, std::forward
在函数中立即使用,并保留参数的正确值类别。
通过意识到这些陷阱并遵循最佳实践,您可以有效地使用完美的转发来编写更高效,更正确的C代码。
以上是什么是C中的完美转发,它如何工作?的详细内容。更多信息请关注PHP中文网其他相关文章!