thread类中构造的函数参数必须是可拷贝的

错误代码

cpp 复制代码
#include <iostream>
#include <string>
#include <thread>

void f(int i, std::string& s) {
    s += " world!";
    std::cout << s << std::endl;
}

int main() {
    std::string s("hello");
    std::thread t(f, 3, s); // 使用std::ref传递s的引用

    t.join(); // 等待线程完成

    return 0;
}

这段代码会导致编译错误,因为在C++中,如果你尝试在线程(std::thread)中传递参数,那么这些参数必须是可拷贝的,或者你需要使用 std::ref 来传递可引用的参数。

在你的代码中,你尝试在线程中传递一个整数 3 和一个 std::string 引用 s,这是不允许的,因为 std::thread 会尝试拷贝参数,而 std::string 是不可拷贝的。当你尝试编译这段代码时,编译器会报错,指出 std::string 无法被拷贝。

要修复这个问题,你可以使用 std::ref 来传递 s 作为引用,这样可以让线程操作同一个 std::string 对象,而不是拷贝它。修改后的代码如下:

cpp 复制代码
#include <iostream>
#include <string>
#include <thread>

void f(int i, std::string& s) {
    s += " world!";
    std::cout << s << std::endl;
}

int main() {
    std::string s("hello");
    std::thread t(f, 3, std::ref(s)); // 使用std::ref传递s的引用

    t.join(); // 等待线程完成

    return 0;
}

这样,线程将能够在 s 上进行操作,而不会触发拷贝构造函数,避免了编译错误。但要注意在线程中访问共享的资源时,需要小心同步操作,以避免竞态条件和数据访问冲突。

相关推荐
fox_lht1 小时前
第一章 不可变的变量
开发语言·后端·rust
骁的小小站2 小时前
Verilator 和 GTKwave联合仿真
开发语言·c++·经验分享·笔记·学习·fpga开发
心灵宝贝4 小时前
申威架构ky10安装php-7.2.10.rpm详细步骤(国产麒麟系统64位)
开发语言·php
lly2024064 小时前
PHP 字符串操作详解
开发语言
大数据张老师4 小时前
数据结构——邻接矩阵
数据结构·算法
低音钢琴5 小时前
【人工智能系列:机器学习学习和进阶01】机器学习初学者指南:理解核心算法与应用
人工智能·算法·机器学习
像是套了虚弱散5 小时前
DevEco Studio与Web联合开发:打造鸿蒙混合应用的全景指南
开发语言·前端·华为·harmonyos·鸿蒙
旭意5 小时前
C++蓝桥杯之结构体10.15
开发语言·c++
深思慎考6 小时前
调用百度云语音识别服务——实现c++接口识别语音
c++·语音识别·百度云
麦麦鸡腿堡7 小时前
Java的单例设计模式-饿汉式
java·开发语言·设计模式