如何避免使用大向量初始化的“编译器限制:编译器堆栈溢出”?

pau*_*ulm 4 c++ visual-c++

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

 The error message indicates as follows: 
 'fatal error C1063: compiler limit: compiler stack overflow'
Run Code Online (Sandbox Code Playgroud)

这是由某些包含以下内容的标头引起的:

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

如何以这种方式使用向量而不会使MSVC崩溃?请注意,该代码在clang和gcc中构建成功。

Ale*_*bin 5

尝试将数据放入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));
}
Run Code Online (Sandbox Code Playgroud)

编辑:感谢伦丁指出有关常量。