Book I'm reading says that this will invoke the constructor for 10 objects of type Test, even though no objects were explicitly created here. Is this true? If so, why? The author doesn't explain this at all.
For each object within the array, 1 call is made to the object's default constructor. The objects were in fact explicitly created - the whole statement is explicit but the creation of the objects appear implicit. If you want to be more explicit, you can use this initialiser list:
1 2
Test test_[3]; // 3 implicitly constructed objects.
Test test_[3] = {(...), (...), (...)}; // 3 explicitly constructed objects.
Alright so I guess my idea of an array is off. In my mind, Test test[10] sets aside space in memory for 10 consecutive Test objects, and the objects are created at a later time during the program (ie, whenever they get explicitly created)
1 2 3 4 5
Test test[10]; //I was thinking nothing gets created here, just memory reserved.
Test testObj1(); //And this is where the object is actually created.
test[0] = testObj1;
...
The objects are guaranteed to be fully constructed by the time the end of the statement is reached (at the semi-colon). The compiler does in fact reserve the memory for those objects. For instance, if no objects were constructed, then this would be invalid:
1 2 3 4 5 6 7 8 9 10
struct X
{
X(int ia_ = 0, int ib_ = 0) : a_(ia_), b_(ib_) { }
int a_, b_;
};
int main()
{
X xs_[2] = {(0, 1), xs_[0]}; // Default constructor call followed by a copy-constructor call.
}
...but it's not.
ResidentBiscuit wrote:
"In my mind, Test test[10] sets aside space in memory for 10 consecutive Test objects, and the objects are created at a later time during the program (ie, whenever they get explicitly created)"
What you're thinking of is placement new:
1 2 3
X *xs_(static_cast<X*>(operatornew [] (2 * sizeof(X)))); // No objects built here.
new(xs_) X(0, 1); // 1 object is now available inside xs_.
Yes, that's why this works (over simplified example)
1 2 3
int x[10];
for(int i ...)
x[i] = 5;
if it isn't constructed you cant assign. Your example test[0] = testObj1; should be an error if Test doesn't have an operator= overload (and probably copy ctor)..
Ooh wow that makes sense now. So if I need a large group of object created at once, with default values, I can just make an array (or any container presumably) of the given type and then they are ready to be used?