std::thread中的参数传递可以用下图解释,首先看代码
#include#include class base { public: base() { std::cout << "base default constructor" << std::endl; } base(const base &base) { std::cout << "base copy constructor" << std::endl; std::cout << "Current thread id: " << std::this_thread::get_id() << std::endl; } base(base &&base) { std::cout << "base move constructor" << std::endl; std::cout << "Current thread id: " << std::this_thread::get_id() << std::endl; } }; void func(base base) { std::cout << "func" << std::endl; } int main() { base base; std::thread t{func, base}; t.join(); return 0; }
编译,这种测试一定要添加-fno-elide-constructors参数,即关闭编译器优化,否则编译器优化会产生和预期不符的结果。
g++ -fno-elide-constructors test.cc -o test
结果
base default constructor base copy constructor Current thread id: 1 base move constructor Current thread id: 1 base move constructor Current thread id: 1 base move constructor Current thread id: 2 func
// 调用一次base的默认构造函数
base base;
// 构造t时传参会调用一次base的拷贝构造函数,
std::thread t{func, base};
// 对象t的构造函数内部会调用std::forward进行参数转发会调用一次base的移动构造函数,可以看到在主线程中执行
std::forward<_Args>(__args)...
// 接着主线程会将base对象移动到子线程,调用一次base的移动构造函数,可以看到在主线程中执行
// func函数接受到的base是rvalue,会调用一次base的移动构造函数,可以看到在子线程中执行
void func(base base)



