在C++中检测意外的消隐维度

Detect accidental elided dimension in C++

本文关键字:消隐 意外 C++ 检测      更新时间:2023-10-16

考虑以下片段:

#include <iostream>
using namespace std;
int a[10][2];
int b[10][2];
int main(){
//intended
cout << a[0][0] - b[0][0] << endl;
//left out dimension by mistake
cout << a[0] - b[0] << endl;
}

显然(或者可能不是根据注释),第二种情况在C和C++中都是有效的指针算术,但在我使用的代码库中,它通常是一个语义错误;在嵌套的for循环中,维度通常被忽略了。有没有任何-W标志或静态分析工具可以检测到这一点?

您可以使用不允许的std::array

using d1=std::array<int, 2>;
using d2=std::array<d1, 10>;
d2 a;
d2 b;
std::cout << a[0][0] - b[0][0] << endl;  // works as expected
std::cout << a[0] - b[0] << endl;        // will not compile

另一个选项是使用具有适当运算符错误处理的专用多维数组库,例如boost::multi_array(http://www.boost.org/doc/libs/1_55_0/libs/multi_array/doc/user.html)。这通常比使用嵌套容器或POD阵列更好。

如果这只是<lt;例如运算符<lt;对于int*可能会有所帮助-您可以重载运算符以生成编译时错误。