如何避免关于未初始化变量的 clang-tidy 警告

How to avoid clang-tidy warnings about uninitialized variables

我正在寻找避免 clang-tidy 警告的最佳方法。

std::istringstream in(line);
float x, y, z, rotx, roty, rotz;
in >> x >> y >> z >> rotx >> roty >> rotz;

->变量'x'未初始化,变量'y'未初始化,...

double min_intensity, max_intensity;    
cv::Point point_min, point_max;
cv::minMaxLoc(input, &min_intensity, &max_intensity, &point_min, &point_max, elliptic_mask_around_center);

->变量'min_intensity'没有初始化,...

我可以为 xy、...以及 min_intensitymax_intensity 分配一个值,但我不明白为什么我应该这样做。

避免此警告的最佳方法是什么?

float x = 0.F; // initialize to a value, but 6 lines, and it makes no sense because x is never 0
float x = NAN; // works but 6 lines, and needs <cmath> inclusion
float x, y, z, rotx, roty, rotz; // NOLINT [not very practical, and means the warning is a false positive]

感谢您的帮助。

通常您应该始终初始化变量,因为读取未初始化的变量是未定义的行为。

当从流中提取失败时,从 C++11 开始分配 0。但是,只有流不处于失败状态时才会出现这种情况。因此,当读取 x 失败时,x 将具有 0 的值,但其他值将具有不确定的值。

您应该始终检查提取是否成功:

if (in >> x >> y >> z >> rotx >> roty >> rotz) { 
     // use x,y,z,rotx,roty,rotz
}

如果你想使用部分输入,即使在某些时候提取失败,你应该单独阅读它们:

if (in >> x) {
     // use x
}
if (in >> y) {
     // use y
}
// ...

如果你这样做,严格来说初始化是没有必要的。但是,从流中读取比初始化变量要昂贵得多,因此要保持一致(参见例如 here) I would suggest to initialize them anyhow. Don't worry about more lines of code, a common recommendation is to declare a single variable per line anyhow (see eg here):

std::istringstream in(line);
float x = 0.0;
float y = 0.0;
float rotx = 0.0;
float roty = 0.0;
float rotz = 0.0;
if (in >> x >> y >> z >> rotx >> roty >> rotz) {
     // extraction succeeded
} else {
     // extraction failed
}