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 上进行操作,而不会触发拷贝构造函数,避免了编译错误。但要注意在线程中访问共享的资源时,需要小心同步操作,以避免竞态条件和数据访问冲突。

相关推荐
weixin_4461224611 分钟前
LinkedList剖析
算法
GiraKoo13 分钟前
【GiraKoo】C++14的新特性
c++
软件黑马王子18 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon20 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
悠悠小茉莉24 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
Da_秀28 分钟前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte34 分钟前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
坏柠39 分钟前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt
泽02021 小时前
C++之红黑树认识与实现
java·c++·rpc
百年孤独_1 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表