xvalue的定义如下:
— An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2). [ Example: The result of calling a function whose return type is an rvalue reference is an xvalue. —end example ]
我们是否会遇到实际需要使用返回类型为右值引用(即 xvalue)的函数的情况?
const int && Foo()
{
// ...
}
移动语义将右值引用作为参数,而不是返回值。所以我认为情况并非如此。
最佳答案
返回右值引用可用于已经将右值作为参数的函数。一个简单的例子:
struct X {
X() = default;
X(X&& other) { std::cout << "move ctor\n"; }
X(X const&) = delete;
void log(std::string const& s){ std::cout << "log: " << s << "\n"; }
};
void sink(X&& x) {
x.log("sink");
}
X&& passOn(X&& in) {
in.log("pass");
return std::move(in);
}
X moveOn(X&& in) {
in.log("move");
return std::move(in);
}
int main() {
sink(passOn(X()));
std::cout << "===============================\n";
sink(moveOn(X()));
}
第二个函数将调用移动构造函数来创建返回的对象,而第一个函数将传递它已经获得的引用。如果我们不返回原始引用而是对被引用对象的一部分的引用,这将更有用,例如
template<class T>
T&& getHead(std::vector<T>&& input) {
return std::move(input.front());
}
关于c++ - 我们什么时候实际上需要 'explicit xvalues' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34870498/