In cpp, is this or something equivalent possible?
Foo bar[23] = Foo();
EDIT:
The motivation for the question was that I think I saw somebody using this syntax
vtkSmartPointer<Foo> bar[23] = vtkSmartPointer<Foo>::New();
and wondered why it compiles and how many new objects are actually created…
Not with this syntax, but if
Foohas a non-trivial defaultconstructor,
will call it for each member of the array. More generally, you can also
write:
The compiler will try to convert each initializer (which can be an
arbitrary expression) into a
Foo, and use that to initialize theelement of the array. If there are not enough initializer expressions,
then all of the following elements will be initialized with
Foo().EDIT:
Since several comments asked for it: if Foo doesn’t have a user defined
constructor, the situation changes (since calling the “constructor”
won’t do anything). In that case, the behavior of:
depends on the variables lifetime: if it has static lifetime, it will be
zero initialized; otherwise, it won’t be initialized at all. In either
case, you can use aggregate initialization to force the initialization
you want:
If there aren’t enough initializers, the remaining elements are zero
initialized, so:
will zero initialize all of the members.
For completeness, I should point out that aggregate initialization
cannot be used for class members: the only ways you can initialize a C
style array member is by means of assignment to each element, in the
body of the constructor, or by copy initialization: define a static
Fooand initialize the member with it.I should probably also point out that all of the above refers to C++03.
C++11 introduced an extended initialization syntax; in particular, you
can use something that looks like aggregate initialization for class
members as well. (I think—I’m not too familiar with C++11, as not
all of my compilers support it yet.)