具有恒定大小数组的警告"ISO C++ forbids variable-size array"

Warning "ISO C++ forbids variable-size array" with constant size array

本文关键字:ISO C++ forbids array variable-size 警告 数组 小数      更新时间:2023-10-16

我有一个c++程序,其中常量存储在类中。在代码中的其他地方,我使用这些常量之一作为数组大小。

下面是一个示例:

常量.h

#ifndef CONSTANTS_H
#define CONSTANTS_H
class Constants
{
public:
    static const unsigned int C_BufferSize;
};
#endif

常量.cpp

#include "Constants.h"
const unsigned int Constants::C_BufferSize(128);

主.cpp

#include "Constants.h"
int main()
{
    char buffer[Constants::C_BufferSize];
    return 0;
}

当我用-std=c++11 -pedantic编译此代码时,我收到以下警告:

main.cpp:5:37: 警告:ISO C++禁止可变长度数组"缓冲区" [-WVLA]

我真的不明白这个错误,因为大小是一个常量,我的猜测是在编译时大小是未知的。

可以使用堆分配表(使用 new 分配)绕过该错误,但我被禁止使用动态内存分配。因此,我正在寻找另一种解决方案。

定义是必需的,并且在链接时进行搜索。所以是的,在编译阶段大小是未知的。

你写的是这个:

class Constants
{
public:
    static const unsigned int C_BufferSize = 128; //initialize here
};

然后只在.cpp文件中提供定义

const unsigned int Constants::C_BufferSize; //no initialization here

但是,将Constants作为命名空间而不是类更有意义:

namespace Constants  //NOTE : a namespace now
{
    static const unsigned int BufferSize = 128; 
};

对我来说似乎更自然。

警告原因 - 正如@nawaz已经提到的(编译时数组中的变量大小 - 可能不是所有编译器都支持/允许)。

可以通过以下方式尝试:

std::vector<char> buffer(Constants::C_BufferSize);

通常,在执行一些char*转换为string时会出现上述问题(受字符缓冲区中的实际数据大小限制)。因此,在这种情况下,可以使用类似的东西;

std::string ConvertCharDataBySizeToString(const char* s, std::size_t size)
{
    std::vector<char> data(s, s+size);
    return ( std::string(data.begin(), data.end()) );
}

参考资料在这里。