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

错误代码

#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 对象,而不是拷贝它。修改后的代码如下:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_WAWA鱼_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值