Már*_*ldi 12 c++ c++11 forwarding-reference
使用转发引用时,将相同的值转发给多个函数是不是一个坏主意?考虑以下代码:
template<typename Container>
constexpr auto
front(Container&& c)
-> typename Container::value_type
{ return std::forward<Container>(c).front(); }
template<typename Container>
constexpr auto
back(Container&& c)
-> typename Container::value_type
{ return std::forward<Container>(c).back(); }
template<typename Container>
constexpr auto
get_corner(Container&& c)
{
return do_something(front(std::forward<Container(c)),
back(std::forward<Container>(c));
}
Run Code Online (Sandbox Code Playgroud)
如果Container是左值引用,则该函数可以正常工作.但是,我担心rvalues传递给它的情况,因为一旦移动操作发生,该值将被无效.我的疑问是:在这种情况下,是否有正确的方法来转发容器,而不会丢失价值类别?
Nic*_*las 14
通常,相同的函数两次转发相同的参数是不合理的.除非它具有该转发参数的接收器将做什么的具体知识.
记住:行为std::forward可以等同于行为std::move,取决于用户传入的参数.而xvalue的行为将取决于接收函数如何处理它.如果接收器采用非常量右值引用,则可能会从该值移动.这会让你拿着一个移动的物体.如果它需要一个值,如果类型支持它,它肯定会从它移动.
因此,除非您具有所使用操作的预期行为的特定知识,否则转发参数不止一次是不安全的.
| 归档时间: |
|
| 查看次数: |
1179 次 |
| 最近记录: |