c++ - 返回值的完美转发,未定义的行为?

标签 c++ c++11 return rvalue-reference perfect-forwarding

我有一组函数,我在其中使用模板特化来对某些值执行转换。但是,对于许多类型,我希望通过不变的方式传递值。

要传递一个不变的值,我有类似下面的函数作为默认值:

template< typename arg >
arg&& convert( arg&& x )
{
    return std::forward<arg>( x );
}

这看起来不错,但根据答案 here它冒着在如下语句中留下悬空引用的风险:

int&& x = convert( 5 );

如果我只在函数参数中使用这个内联,是否可以避免这种风险?

例如,如果我做类似...的事情,我会遇到未定义的行为吗

void foo( int&& x )
{
    // Do something with x...
}

foo( convert( 5 ) );

最佳答案

For example, do I run into undefined behaviour if I do something like...

没有。规则,来自[class.temporary] ,强调我的,是:

A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing the call.

我们的临时对象 (5) 在函数调用中绑定(bind)到一个引用参数(到 convert() 中的 arg&&),所以它一直持续到完整表达式的末尾(即 foo(convert(5)) 的全部)。所以这很好,只要您不让对 x 的引用从 foo() 中逃脱。

关于c++ - 返回值的完美转发,未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46506402/

相关文章:

c++ - 'this' 参数的类型为 const 但函数未标记为 const

json - 如何在 C++ 中使用 Boost 访问嵌套的 json 数组元素

c++ - 使用 std::move 有任何性能优势吗?

c++ - 澄清智能指针的 operator* 和 operator-> 重载

c++ - 模板中的异常

c++ - 如何使函数模板仅适用于特定命名空间中的类型?

c - 这是什么意思?返回函数()

php - 从php中获取python脚本的返回值

从函数返回时 C 数组发生变化

c++ - 不能使用 CV_32UC1