问题
Neither g++ (4.4 and 4.6) nor clang++ (3.2) nor coverity, with -Wall and -Wextra (+ some others) or -Weverything respectively gives me a warning for the following code snippet:
class B {
char *t2;
char *t;
public:
B() : t2(t), t(new char[100]) {}
};
I would at least expect a small warning about the usage of uninitialized (member-) variables.
Is there something I'm missing? Is this a wanted "no-warning"-scenario. I have (now had) at least one bug in my software which was hard to find.
EDIT: As can be read in this new question I realized that coverity warns about this problem in some cases.
回答1:
There is no good reason not to issue a warning here.
G++ isn't smart enough to diagnose unintialized members in constructors, see http://gcc.gnu.org/PR2972
I have a work-in-progress patch to fix it which I hope to finish "some time this year"
Even with my patch I'm not sure G++ would warn, because t2
is initialized, but it's initialized to an indeterminate value. For the compiler to track that is not trivial, but should be possible (so I'm surprised even Coverity misses it.) Run-time tools such as valgrind
get it right though.
When I revisit my patch I'll consider this case and see whether I can make it warn, without adding too much overhead (currently my patch checks whether members without an initializer would leave data uninitialized, to catch this I would need to also check members with an initializer and check whether that initializer relies on another member which isn't yet initialized, which would need to be checked for every member, which might have an effect on compilation speed for classes with lots of members.)
回答2:
The C++ standard says that using uninitialized variables leads to undefined behaviour. It does not mandate that the compiler issue a diagnostic about it. So getting a warning or not is a QOI (Quality of Implementation) thing.
来源:https://stackoverflow.com/questions/14139265/c-init-list-using-non-initialized-members-to-initialize-others-gives-no-warni