Default Initialization in C ++

Let's say I have a structure that looks like this (POD):

struct Foo { int i; double d; }; 

What is the difference between the two lines:

 Foo* f1 = new Foo; Foo* f2 = new Foo(); 
+7
c ++ constructor initialization default
Jun 01 '10 at 16:38
source share
3 answers

The first leaves the values ​​uninitialized; the second initializes them to zero. This applies only to POD types that do not have constructors.

+12
Jun 01 '10 at 16:57
source share

I do not understand anything. Foo() allowed, even if it makes no sense ... I tried changing the struct to class and tried diff for the generated exe, and they turned out to be the same, which means that a class without a method is similar to a structure from a practical and "efficient" point of view .

But : if you use only one alternative, it doesn’t matter when storing a struct or class , it happens that new Foo and new Foo() give executable files that are different! (At least using g ++) Ie

 struct Foo {int i;  double d;  }
 int main () {Foo * f1 = new Foo;  delete f1;  }

compiled to something other than

 struct Foo {int i;  double d;  }
 int main () {Foo * f1 = new Foo ();  delete f1;  }

and the same thing happens with class instead of struct . To find out what the difference is, we need to look at the generated code ... and know whether it is g ++ idiocy or not, I should try another compiler, but I only have gcc and no time to parse asm g ++ output ...

In any case, from the "functional" (practical) point of view, this is one and the same.

Add

In the end, it’s always better to know or do a deeper study of some common human problems on Q / A sites ... the only difference is in the code generated by the g ++ in () and no () cases,

     movl $ 0, (% eax)
     fldz
     fstpl 4 (% eax)

which is a fragment that initializes the value of the 0 / 0.0 int and double structures ... so Seymour knows this better (but I could detect it without knowing if I looked at asm first!)

+1
Jun 01 '10 at 16:50
source share

By the link that I posted.

In C ++, the only difference between a class and a structure is that class members are private by default, and struct members are public by default. Thus, structures can have constructors, and the syntax is the same as for classes.

Constructor Design Information

-2
Jun 01 '10 at 16:44
source share



All Articles