这是一个简单的测试用例,编译时没有任何警告。看起来像是一个常见错误,但在这种情况下,clang、gcc 和 visual studio 不会发出警告。为什么?
class Image {
private:
int width, height;
int* array;
public:
Image(int _width, int _height);
void crashTest();
};
Image::Image(int _width, int _height)
{
array = new int[width * height];
// ^^^^^ ^^^^^^ this is wrong
// I expect a warning here e.g.: 'width is uninitialized here'
width = _width;
height = _height;
}
void Image::crashTest()
{
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
array[x + y * width] = 0;
}
}
int main()
{
const int ARRAY_SIZE = 1000;
Image image(ARRAY_SIZE, ARRAY_SIZE);
image.crashTest();
return 0;
}
例如:
g++ -Wall -Wextra -O2 -Wuninitialized test.cpp
clang++ -Wall -Wextra -O2 -Wuninitialized test.cpp
没有给我警告
最佳答案
这个老问题的后续行动:通过使用 -Weffc++
启用来自“Effective C++”的警告,您可以使用 g++ 获得您正在寻找的警告。这将提示未明确初始化的成员变量。
这可能过于激进,因为它还会提示具有未显式初始化的默认构造函数的类成员。
我还没有看到 Clang 的等效选项——我同意关于具有未初始化原始数据成员的类的警告会非常有用。
关于c++ - 为什么我没有收到有关在 ctor 中访问未初始化成员变量的编译器警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23937605/