GCC Warning [Wuninitialized]

Why does GCC 4.7 complain when creating an instance of a class inside a function (with a pointer)?

Poorly:

#include "foo.h"

int fn () {
    Foo *foo;
    foo->method();

   return 0;
}

main.cpp: In the member function 'int foo ()': main.cpp: 21: 52: warning: 'fn', the function uninitialized in this can be used [-Uniminization]

Good:

#include "foo.h"

Foo *foo;

int fn () {
    foo->method();

   return 0;
}

Good:

#include "foo.h"

int fn () {
    Foo foo;
    foo.method();

   return 0;
}
+5
source share
5 answers

There is a difference between Foo * foo;and Foo foo;The first declares a pointer to Foo, the second declares and calls the default constructor Foo.

EDIT: Perhaps you wanted to write Foo * foo= new Foo();to allocate Fooon a heap that could survive a function call.

+6
source

(), foo . , Foo* foo = NULL;, ( ).

() , C NULL 0 , .

() , , , , , 2. , , method Foo.

+5

Foo* foo; foo->method() . foo - , , undefined. , , , . , , .

+2

foo - , . class Foo .

"" 0, foo . undefined , foo .

+2

, , . . foo - undefined. , , foo.

, foo ( Foo *) int. int Foo. , foo. , :

Foo* foo = new Foo;

newreturns the address at which the new Foo object was created. this will remove your warning :)

+2
source

All Articles