我有一组函数,我在其中使用模板特化来对某些值执行转换。但是,对于许多类型,我希望通过不变的方式传递值。
要传递一个不变的值,我有类似下面的函数作为默认值:
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/