You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

std::thread构造函数传参报错:指针与引用参数不匹配求助

多线程编译错误解决方案

错误原因

你的线程函数test1和test2定义为接收int&(整数引用)类型参数,但创建线程时传递的是int*(整数指针)类型的pI,类型不匹配。此外,std::thread在传递参数时会默认对实参进行decay转换(即把引用、指针等转换成值类型存储),即使传递的是int&,也会被转成值,导致无法匹配需要引用参数的函数,触发编译断言失败。

解决方法

有两种可行的修改方式:

方式一:修改线程函数参数为指针

把线程函数的参数类型从int&改为int*,并调整函数内部的访问逻辑:

#include <iostream>
#include <thread>
#include <chrono>

using namespace std::chrono_literals;

void test1(int *i){
    while(*i < 10){
        if (*i % 2 == 0){
            std::cout << "Thread 1 " << *i << std::endl;
            std::this_thread::sleep_for(2000ms);
            (*i)++; // 注意括号,避免运算符优先级问题
        }
    }
}

void test2(int *i){
    while(*i < 10){
        if (*i % 2 != 0) {
            std::cout << "Thread 2 " << *i << std::endl;
            std::this_thread::sleep_for(2000ms);
            (*i)++;
        }
    }
}

int main(){
    int i = 0;
    int *pI = &i;
    std::thread firstThread(test1, pI);
    std::thread secondThread(test2, pI);
    firstThread.join();
    secondThread.join();
    return 0;
}

方式二:用std::ref传递引用

保持线程函数的引用参数不变,创建线程时用std::ref包装变量,显式传递引用:

#include <iostream>
#include <thread>
#include <chrono>
#include <functional> // 需包含此头文件使用std::ref

using namespace std::chrono_literals;

void test1(int &i){
    while(i < 10){
        if (i % 2 == 0){
            std::cout << "Thread 1 " << i << std::endl;
            std::this_thread::sleep_for(2000ms);
            i++;
        }
    }
}

void test2(int &i){
    while(i < 10){
        if (i % 2 != 0) {
            std::cout << "Thread 2 " << i << std::endl;
            std::this_thread::sleep_for(2000ms);
            i++;
        }
    }
}

int main(){
    int i = 0;
    std::thread firstThread(test1, std::ref(i)); // 用std::ref包装i
    std::thread secondThread(test2, std::ref(i));
    firstThread.join();
    secondThread.join();
    return 0;
}

注意:第二种方式必须包含<functional>头文件,否则std::ref会未定义。

内容的提问来源于stack exchange,提问作者nakul sawant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:09:58