栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

std::thread参数传递

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

std::thread参数传递

std::thread参数传递
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)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/691211.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号