Is it well-defined to cast xvalues to lvalues for passing to functions?

此生再无相见时 提交于 2019-12-03 10:38:18

As you said, you took care to not let any pointer or reference to the temporaries escape their scope.
Using your lvalue-function (mine is called no_move) makes it easier to break that stricture inadvertently.

Next, let's look at what xvalues are: Expiring objects, but objects nevertheless.
This means, you can ignore they are on their funeral tour (if you pass them to a function, that function will naturally do so, unless you ask to take advantage).

The last point you mentioned was calling with a prvalue, which is most certainly not an object.
But even that is not a problem, as on calling the function, a temporary will be created.
And that temporary will naturally also survive to the end of the statement.

As an aside, using std::remove_reference_t<T>& is unneccessary for the return-type of lvalue, you can use T& directly and rely on the reference-collapsing-rules. Also, the static_cast and inline are superfluous.

template <typename T> constexpr T& lvalue(T&& r) noexcept {return r;}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!