Question

I read a book S. Lippman "inside c++ object model", is there such code

class Foo { public: int val; Foo *pnext; };
void foo_bar()
{
// Oops: program needs bar's members zeroed out
Foo bar;
Foo* baz = new Foo(); // this line i added myself
if ( bar.val || bar.pnext )
// ... do something
// ...
}

and it says that "A default constructor is not synthesized for this code fragment.

Global objects are guaranteed to have their associated memory "zeroed out" at program start-up. Local objects allocated on the program stack and heap objects allocated on the free-store do not have their associated memory zeroed out; rather, the memory retains the arbitrary bit pattern of its previous use."

In this code the baz object was created on the heap, and according to what has been said above this object is not global and it will not be called the default constructor. I understand correctly ?

Was it helpful?

Solution

The parentheses in new Foo() specify value initialisation; this basically means that each member is zero-initialised. If instead you said new Foo, then the members would be left uninitialised, as they are for your automatic variable.

Unfortunately, to value-initialise the automatic variable, you can't write Foo bar(), since that declares a function. You'll need

Foo bar{};        // C++11
Foo bar = Foo();  // Historical C++

OTHER TIPS

When you do this:

Foo* baz = new Foo();

you are dynamically allocating a Foo instance and value-initializing it. For PODs, this means the members get zero-initialized. If you had said this (assuming non-global context):

Foo* baz = new Foo;

then the Foo instance would be default initialized, which would mean no initialization of its members is performed, since they are PODs.

This also applies to automatic storage instances:

Foo f0; // default initializaiton: members not zeroed out.
Foo f1 = Foo(); // value initialization: members zeroed out.
Foo f2{}; // C++11 value initialization: members zeroed out.
Foo f3(); // Ooops! Function declaration. Something completely different.

If a class have no default constructor (and no other constructor), the compiler will create one for you. It has to, or you would not be able to create instances of the class. However, the generated default constructor will not do anything.

What adding the empty set of parentheses in new Foo() does, is to value initialize the allocated object, which means the members gets initialized to their "default" values, which is zero for integer and floating point values, and nullptr for pointers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top