在C++中检测意外的消隐维度
Detect accidental elided dimension in C++
考虑以下片段:
#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*可能会有所帮助-您可以重载运算符以生成编译时错误。
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 复制列表初始化的隐式转换的等级是多少
- 在C++中对T*类型执行std::move的意外行为
- 生成文件不对文件使用隐式规则
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 处理除以零会导致<csignal>意外行为
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 返回值优化:显式移动还是隐式
- 隐式常量/非常量运算符布尔
- vscode下的Arduino代码出现意外编译错误
- 使用++运算符会导致意外的结果
- 套接字读取后,我在缓冲区中看到意外输入
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 意外缺少隐式声明的复制/移动构造函数
- 在C++中检测意外的消隐维度
- 线循环的背面消隐
- C/C++OpenGL遮挡消隐
- 一次执行后,嵌套for循环出现意外/未见的中断:高斯消去