如何避免大矢量初始化"compiler limit: compiler stack overflow"?

How to avoid "compiler limit: compiler stack overflow" with large vector inits?

本文关键字:compiler stack overflow limit 何避免 初始化      更新时间:2023-10-16

在我的单元测试中,我得到了以下编译器错误:

 The error message indicates as follows: 
 'fatal error C1063: compiler limit: compiler stack overflow'

这是由一些生成的标头引起的,这些标头包含:

std::vector<unsigned char> GetTestData()
{
     return { 0x1, 0x2, 0x3 }; // Very large 500kb of data
}

如何在不破坏MSVC的情况下以这种方式使用矢量?请注意,代码在clang和gcc中构建正常。

尝试将数据放入const静态数组,然后使用向量的范围ctor:

std::vector<unsigned char> GetTestData()
{
    static const unsigned char data[] = { 
        0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0,
             ...
    }; // Very large 500kb of data
    return std::vector<unsigned char>(data, data + sizeof(data));
}

编辑:感谢Lundin指出const。

尝试构建一个大数组进行初始化,而不是直接使用初始化器。

std::vector<unsigned char> GetTestData()
{
     static const unsigned char init[] = { 0x1, 0x2, 0x3 }; // Very large 500kb of data
     return std::vector<unsigned char>(std::begin(init), std::end(init));
}

即使它在clang和gcc中构建良好,我也不建议按值返回这样的大向量。如果您正在处理的数据是不可变的,我会将其作为常量引用返回,如:

// EDIT Moved vector outside of function
static const std::vector<unsigned char> static_v({ 0x1, 0x2, 0x3 });
    const std::vector<unsigned char> & GetTestData()
    {
    return static_v;
    }
相关文章: