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

C++中如何从POSIX线程返回vector<pair<int,string>>类型数据

POSIX线程返回vector<pair<int,string>>的实现方法

和返回int类型的思路一致,核心是在堆上分配容器对象(线程栈内存会随线程退出释放,不能用来存储返回数据),但因为vector是C++对象,要注意用new而非malloc(malloc仅分配内存,不会调用对象构造函数,会导致未定义行为)。

完整实现代码

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

// 线程函数:返回vector对象的指针(转成void*)
void* myfunc(void* args) {
    // 在堆上构造vector对象
    std::vector<std::pair<int, std::string>>* result = new std::vector<std::pair<int, std::string>>();
    
    // 向容器中添加数据
    result->emplace_back(1, "苹果");
    result->emplace_back(2, "香蕉");
    result->emplace_back(3, "樱桃");
    
    return static_cast<void*>(result);
}

int main() {
    pthread_t thread_var;
    // 创建线程
    int create_ret = pthread_create(&thread_var, nullptr, myfunc, nullptr);
    if (create_ret != 0) {
        std::cerr << "线程创建失败" << std::endl;
        return 1;
    }
    
    void* received;
    // 等待线程结束并获取返回值
    pthread_join(thread_var, &received);
    
    // 将void*转回vector指针
    auto result_vec = static_cast<std::vector<std::pair<int, std::string>>*>(received);
    
    // 处理返回的数据
    for (const auto& item : *result_vec) {
        std::cout << "序号:" << item.first << ",内容:" << item.second << std::endl;
    }
    
    // 释放堆内存,避免泄漏
    delete result_vec;
    
    return 0;
}

关键注意事项

  • 必须用new创建vector:vector是带构造逻辑的C++对象,malloc无法完成初始化,直接使用会触发崩溃或未定义行为。
  • 用完记得释放内存:返回的vector在堆上,主线程使用后必须用delete回收,否则会造成内存泄漏。
  • 参数传递(可选):如果需要给线程传参,同样可以通过args指针传入,注意参数的生命周期——要么用堆分配,要么保证主线程在子线程使用期间不释放参数内存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:45:33