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

相关推荐
_深海凉_20 小时前
LeetCode热题100-移除元素
数据结构·算法·leetcode
Makoto_Kimur20 小时前
Java Scanner 的 ACM 常用输入模板
java·数据结构·算法
A.A呐20 小时前
【C++第二十八章】单例模式
c++·单例模式
逆境不可逃20 小时前
【后端新手谈09】深入浅出短链接:从原理到实战开发
算法·面试·职场和发展
Michelle802320 小时前
R语言 for循环
开发语言·r语言
小碗羊肉20 小时前
【从零开始学Java | 第三十二篇】方法引用(Method Reference)
java·开发语言
DeepModel20 小时前
通俗易懂讲透随机梯度下降法(SGD)
人工智能·python·算法·机器学习
玖釉-20 小时前
C++ 硬核剖析:if 语句中的“双竖杠” || 到底怎么运行的?
开发语言·c++
满满和米兜20 小时前
【Java基础】- 集合-HashSet与TreeSet
java·开发语言·算法
无尽的罚坐人生20 小时前
hot 100 73. 矩阵置零
线性代数·算法·矩阵