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

相关推荐
WolfGang0073211 分钟前
代码随想录算法训练营 Day20 | 回溯算法 part02
算法
YXXY3133 分钟前
前缀和算法
算法
客卿1234 分钟前
滑动窗口--模板
java·算法
xiaoye-duck11 分钟前
【C++:unordered_set和unordered_map】 深度解析:使用、差异、性能与场景选择
开发语言·c++·stl
_日拱一卒22 分钟前
LeetCode:滑动窗口的最大值
数据结构·算法·leetcode
zjjsctcdl26 分钟前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
格林威30 分钟前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
codeの诱惑32 分钟前
推荐算法(一):数学基础回顾——勾股定理与欧氏距离
算法·机器学习·推荐算法
落樱弥城33 分钟前
Vulkan Compute 详解
算法·ai·图形学
老约家的可汗33 分钟前
list 容器详解:基本介绍与常见使用
c语言·数据结构·c++·list