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

相关推荐
foundbug9994 小时前
Polar Code 编解码 MATLAB 实现
开发语言·算法·matlab
李小小钦4 小时前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
W是笔名4 小时前
python___容器类型的数据___列表
开发语言·windows·python
跨境数据猎手4 小时前
多平台电商比价系统从零搭建合规
开发语言·爬虫·架构
卷无止境4 小时前
SFML 深度解读:一个教科书级 C++ 多媒体库的内功心法
c++·后端
技术不好的崎鸣同学4 小时前
[ACTF2020 新生赛]Include 思路及解法
算法·安全·web安全
先吃饱再说4 小时前
一篇吃透树的遍历:递归与迭代的完整拆解
数据结构·算法
hai3152475434 小时前
九章编译法:DEEPSEEK V3.2汇编编译实例
java·开发语言
lkshop4 小时前
Next.js 网站 SEO 优化:从 SSR、Sitemap 到结构化数据
开发语言·javascript·ecmascript
Robot_Nav5 小时前
贪心算法、动态规划与 MPPI 算法结构相关力扣题目汇总
算法·贪心算法·动态规划