gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:20:35 25 4
gpt4 key购买 nike

我正在寻找使用 clang-tidy 避免 cppcoreguidelines-init-variables 警告的最佳方法。

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 )我建议无论如何都要初始化它们。不要担心更多的代码行,一个常见的建议是无论如何每行声明一个变量(参见例如 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
}

关于c++ - 如何避免关于未初始化变量的 clang-tidy 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68526284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com