On Monday, 5 January 2015 17:57:16 UTC+2, Joseph Hesse wrote:
> Hi,
>
> Can someone provide me with an example of a function returning an &&.
Who returns it must be make sure that the object does not go out of scope
before it is used by caller.
struct Thing
{
Resource r;
// return reference to member; caller can use it for copying
Resource const& resource() const
{
return r;
}
// return rvalue reference to caller; caller can use it for moving
Resource&& stealResource() &&
{
return std::move(r);
}
};
> I tried
> int && f(int x) {
> return x;
> }
> but it didn't work.
This is trying to return dangling reference to function's by-value parameter.
Changing to 'return std::move(x);' will succeed in returning that dangling
reference. You don't want to return dangling references because it is undefined
behaviour.