为什么 std::thread 可以返回但不可复制的限制?

Con*_*lyM 2 c++ compilation c++11 stdthread

我对下面代码的成功编译感到非常困惑。函数“g”中的变量“t”显然是左值。当'g'返回到主函数时,'t'应该被复制。但是线程对象是不可复制的,那为什么会编译成功呢?

#include <thread>

void some_other_function(int) {
    return;
}
std::thread g()
{
    std::thread t(some_other_function,42);
    return t;
}

int main() {
    g();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

int*_*jay 5

当您使用return局部变量时,将使用移动构造函数而不是复制构造函数(如果可用)。虽然std::thread没有复制构造函数,但它有一个移动构造函数,所以这可以工作。

请参阅Automatic_move_from_local_variables_and_parameters

由于 NRVO(命名返回值优化),编译器也可能会完全消除移动,但这并不能保证。