I'm quite confused about the successful compilation of the code below. The variable 't' in the function 'g' is obviously a left-value. When 'g' returns to the main function, 't' should be copied. However, the thread object is not copyable, so why does it compile successfully?
#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;
}
When you return
a local variable, the move constructor will be used instead of the copy constructor (if available). While std::thread
does not have a copy constructor, it does have a move constructor so this will work.
See Automatic_move_from_local_variables_and_parameters
It's also possible that the compiler will elide the move completely due to NRVO (named return value optimization), but this isn't guaranteed.