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

C++如何向vector插入元素供后续调用?空vector返回问题排查

问题分析
  • 核心问题:你定义的nodelinks向量全程没有执行插入元素的操作,所有计算结果都未存入容器,因此返回为空。
  • 隐藏风险:当前代码中mins、maxs是函数栈上的临时变量,若直接存储其指针到返回值中,函数结束后变量内存被回收,后续访问会触发野指针类未定义行为。
修复方案

如果你需要保持原有返回类型std::vector<const Vector *>不变,修改后的代码如下:

std::vector<const Vector *> ServerDLL::GetNodeLinks() const
{
    std::vector<const Vector *> nodelinks;
    if (!WorldGraph) {
        return nodelinks;
    }

    const int count = *reinterpret_cast<int *>(reinterpret_cast<uintptr_t>(WorldGraph) + offm_cLinks);
    uintptr_t link = *reinterpret_cast<uintptr_t *>(reinterpret_cast<uintptr_t>(WorldGraph) + offm_pLinkPool);
    entvars_t *linkent = *reinterpret_cast<entvars_t**>(reinterpret_cast<Vector *>(link + offm_vecLinkEnt));

    // 遍历存入所有src、dest节点指针
    for (int i = 0; i < count; ++i) {
        nodelinks.push_back(reinterpret_cast<Vector *>(link + offm_vecSrcNode + offm_vecOrigin));
        nodelinks.push_back(reinterpret_cast<Vector *>(link + offm_vecDestNode + offm_vecOrigin));
        link += size_CLink;
    }

    // 动态分配mins、maxs内存,避免函数退出后内存被回收
    Vector* mins = new Vector(linkent->mins);
    Vector* maxs = new Vector(linkent->maxs);
    Vector origin = linkent->origin;

    for (int i = 0; i < 3; ++i) {
        (*mins)[i] += origin[i];
        (*maxs)[i] += origin[i];
    }

    // 存入处理后的mins、maxs
    nodelinks.push_back(mins);
    nodelinks.push_back(maxs);

    return nodelinks;
}
注意事项
  • 上述代码中动态申请的mins、maxs内存,需要你在业务逻辑使用完nodelinks后手动释放,避免内存泄漏。
  • 如果你不想手动管理内存,可以将返回类型修改为std::vector<Vector>直接存储值,无需操作指针也不会有内存风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:39:00