Also syntax for new operator is typename *variable_name = new typename, but here T()
will be a temporary object but not type name.
Similarly to the Most Vexing Parse, T()
has different meanings depending on context. It does not always produce a temporary, but generally initializes some new anonymous object or subobject. The object might be
- a temporary if
T()
is in an expression,
- base subobject if
T()
appears before the body in a constructor, or
- the referent of the pointer if
T()
appears after new
. Note that the pointer has a name, but the object is anonymous.
new T
and new T()
do slightly different things: for some types, new T
leaves values uninitialized. (The official term is default-initialization.) There is no corresponding grammatical construct for base subobjects or temporaries: base subobjects are default-initialized by omitting the initializer, and temporaries are not allowed to be default-initialized. The difference is minor, since in all these cases a constructor will be called if you defined one, and a constructor should always be defined, and it should always initialize all members. Exceptions are fundamental types such as int
and simple structures like std::array<char, 1000>
.
To be on the safe side, it's best to avoid new T
in favor of new T()
just to make sure that things are nicely zeroed out in the absence of a constructor.