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

如何在C++中从线程返回vector并正确转换该vector类型?

如何在C++中通过pthread线程返回vector?

你的代码存在两个关键问题,导致vector的转换和返回出现异常:

  1. 线程函数返回类型错误
    pthread库要求线程函数的返回类型必须是void*,但你的函数定义为void get_child_tree_thread(void *arguments),这会导致返回指针的行为属于未定义行为,必须修正函数签名。

  2. 冗余的强制转换
    pthread_join得到的threadResult本身就是void*类型,不需要进行两次重复的强制转换,直接转换为std::vector<Data_1>*即可。

修正后的完整代码

#include <iostream>
#include <vector>
#include <pthread.h>
#include <string>
#include <cerrno>
#include <cstdlib>

using namespace std;

struct Data_1{
    string stm;
    // 其他成员...
};

// 修正线程函数的返回类型为void*
void* get_child_tree_thread(void *arguments){    
    vector<Data_1> v_result;

    Data_1 a,a1;
    a.stm = "1234";
    a1.stm = "1235";
    
    v_result.push_back(a);
    v_result.push_back(a1);
    
    // 直接构造新vector并拷贝内容,简化代码
    std::vector<Data_1>* vec = new std::vector<Data_1>(v_result);
    
    return vec;
}

int main(void)
{
    pthread_t thread;
    if (pthread_create(&thread,NULL, get_child_tree_thread,NULL)){
        cerr << "create thread error: " << strerror(errno) << endl;         
        exit(EXIT_FAILURE);
    }
    
    // 不需要sleep,pthread_join会自动等待线程结束
    void *threadResult = NULL;
    cout << "main waiting for thread..." << endl;
    pthread_join(thread, &threadResult);
        
    // 使用static_cast进行类型转换,更符合C++类型安全规范
    std::vector<Data_1> *v_child_out = static_cast<std::vector<Data_1>*>(threadResult);
    
    cout << "p join v_child_out size: " << v_child_out->size() << endl;       
    
    // 必须释放线程中new分配的内存,避免内存泄漏
    delete v_child_out;
  
    return 0;
}

额外注意事项

  • 优先使用static_cast替代C风格的强制转换,能在编译期提供更多类型检查,避免潜在错误。
  • 线程中用new创建的vector必须在主线程中用delete释放,否则会造成内存泄漏。
  • 不要依赖sleep等待线程完成,pthread_join是线程同步的可靠方式,它会阻塞主线程直到目标线程执行完毕。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:47:06