samedi 30 septembre 2017

Perfect forwarding of return values, undefined behaviour?

I have a set of functions where I employ template specialisation to perform transforms on certain values. However, for many types I want to pass the values through unchanged.

To pass a value unchanged I have something like the following function as the default:

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

This seems great but according to the answer here it runs the risk of leaving a dangling reference in a statement like:

int&& x = convert( 5 );

If I only use this inline in function arguments, is this risk avoided?

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

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

foo( convert( x ) );

Aucun commentaire:

Enregistrer un commentaire