std::thread参数传递

本文探讨了C++标准库中的std::thread在参数传递时如何调用构造函数。通过一个示例代码展示了关闭编译器优化后,线程创建过程中拷贝构造函数和移动构造函数的调用情况。在主线程中,参数被传递时触发了拷贝和移动构造函数,而在子线程中执行函数时再次调用了移动构造函数。
摘要由CSDN通过智能技术生成

std::thread参数传递


std::thread中的参数传递可以用下图解释,首先看代码

#include <iostream>
#include <thread>

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值