Why GCC 4.7 complains when instantiate a class inside a function (with a pointer)?
Bad:
#include "foo.h"
int fn () {
Foo *foo;
foo->method();
return 0;
}
main.cpp: In member function 'int foo()': main.cpp:21:52: warning: 'fn' may be used uninitialized in this function [-Wuninitialized]
Good:
#include "foo.h"
Foo *foo;
int fn () {
foo->method();
return 0;
}
Good:
#include "foo.h"
int fn () {
Foo foo;
foo.method();
return 0;
}
If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn't know this. To suppress the warning, you need to provide a default case with assert(0) or similar code. This option also warns when a non-volatile automatic variable might be changed by a call to longjmp.
Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error. The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC.
GCC 4.3+ now has -Q --help=warnings , and you can even specify --help=warnings,C to just print out the C related warnings.
To disable a set of warnings for a given piece of code, you have to start with a “push” pre-processor instruction, then with a disabling instruction for each of the warning you want to suppress, and finish with a “pop” pre-processor instruction.
There's a difference between Foo * foo;
and Foo foo;
The first declares a pointer to a Foo, the second declares & invokes the default-constructor of a Foo.
EDIT: Maybe you meant to write Foo * foo= new Foo();
, in order to allocate a Foo
on the heap which can outlive the function call.
The first (bad) one, foo is pointing to a garbage pointer. You could remove the warning by initializing it like Foo* foo = NULL;
but then you'd get an error when you tried to dereference it (runtime error).
The second (good) one doesn't complain because C automatically initializes variables in the translation unit scope to NULL or 0 or the appropriate equivalent if they're not already initialized.
The last (good) one doesn't complain because you are calling a method on the object and the assignment of the function pointer is done by the compiler, similar but not the same as number 2. So the compiler already knows the address of the method method
and has assigned that address to the appropriate location on the Foo
struct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With