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 ?
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++