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

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

在我的单元测试中,出现以下编译器错误:

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

这是由某些生成的 headers 引起的,其中包含:

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

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

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

// 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;
    }

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

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));
}

尝试将数据放入常量静态数组,然后使用向量的范围构造函数:

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。