c++ - 我们什么时候实际上需要 'explicit xvalues' ?

标签 c++ c++11

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()));
}

Live demo →

第二个函数将调用移动构造函数来创建返回的对象,而第一个函数将传递它已经获得的引用。如果我们不返回原始引用而是对被引用对象的一部分的引用,这将更有用,例如

template<class T>
T&& getHead(std::vector<T>&& input) {
    return std::move(input.front());
}

关于c++ - 我们什么时候实际上需要 'explicit xvalues' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34870498/

相关文章:

c++ - 无法在 Windows 上编译 Apache 2.0.63

c++ - 向 C++ 代码添加人为延迟时会出现奇怪的结果。嵌入式Linux

C++、多态和迭代器

c++ - 我这里可以不使用线程同步吗?

c++ - Std::copy 在调试版本中失败

java - 用 c 编写一个函数,其中包含以下语句序列 [不会编译]

c++ - 如何避免为采用编译时值的运算符编写显式模板参数?

c++ - 根据当前时间返回下一整秒

c++ - 为什么锁定 std::mutex 不会阻塞线程

c++ - valgrind/callgrind 可以在发布的可执行 C++ 程序上工作吗?