Pee*_*oot 140 c++ g++ compiler-warnings
g ++ -Wall选项包括-Wreorder.该选项的作用如下所述.我不清楚为什么有人会关心(特别是在-Wall中默认打开它).
-Wreorder (C++ only)
Warn when the order of member initializers given in the code does not
match the order in which they must be executed. For instance:
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler will rearrange the member initializers for i and j to
match the declaration order of the members, emit-ting a warning to that
effect. This warning is enabled by -Wall.
int*_*nt3 238
考虑:
struct A {
int i;
int j;
A() : j(0), i(j) { }
};
Run Code Online (Sandbox Code Playgroud)
现在i被初始化为某个未知值,而不是零.
或者,初始化i可能具有一些副作用,顺序很重要.例如
A(int n) : j(n++), i(n++) { }
Run Code Online (Sandbox Code Playgroud)
Ste*_*sop 37
问题是有人可能会在构造函数中看到成员初始化列表,并认为它们是按照该顺序执行的(先是j,然后是i).它们不是,它们按照成员在类中定义的顺序执行.
假设你写了A(): j(0), i(j) {}.有人可能会读到这一点,并认为我最终得到的值为0.它没有,因为你用j初始化它,其中包含垃圾,因为它本身并没有被初始化.
警告提醒你写A(): i(j), j(0) {},希望看起来更可疑.
如果您的初始化程序有副作用,这可能会咬你.考虑:
int foo() {
puts("foo");
return 1;
}
int bar() {
puts("bar");
return 2;
}
struct baz {
int x, y;
baz() : y(foo()), x(bar()) {}
};
Run Code Online (Sandbox Code Playgroud)
上面将打印"bar"然后打印"foo",即使直觉上会假设订单是在初始化列表中写的.
或者,如果x和y某些用户定义类型具有构造函数,则该构造函数也可能具有副作用,具有相同的非显而易见的结果.
当一个成员的初始化程序引用另一个成员时,它也可以表现出来.
存在警告是因为如果您只是阅读构造函数,它看起来就像j之前被初始化一样i.如果用于初始化另一个,则会成为问题,如
struct A {
int i;
int j;
A(): j (0), i (this->j) { }
};
Run Code Online (Sandbox Code Playgroud)
当你只看构造函数时,这看起来很安全.但实际上,j在用于初始化时尚未初始化i,因此代码将无法按预期工作.因此警告.
| 归档时间: |
|
| 查看次数: |
45828 次 |
| 最近记录: |