I searched a bit, and it seems that I cannot decide on the constructor to use when allocating arrays of classes or structs with the new operator. However, this seems too restrictive to me. Is there a way? Because if not, then it means that you cannot dynamically allocate arrays of a data type that doesn't have a parameter-less constructor.
What's stopping you from looping through your new array and simply replacing the elements with an object initialized with the constructor you actually want?
What performance hit do you see in the following constructor when compared to the one that follows it?
1 2 3 4 5 6 7 8 9
class CFoo
{
int m_myInt;
public:
CFoo(void)
{
m_myInt = 0;
}
}
1 2 3 4 5 6 7
class CFoo
{
int m_myInt;
public:
CFoo(void) : m_myInt(0)
{ }
}
I would say it is absolutely minimal, yet C++ went the distance and provided the better (second) approach. I am (or was) therefore reluctant to believe that they left out this ability for arrays.
The "hit" is that you run 2x the number of constructors as necessary. When the array is allocated, the default
constructor is invoked for each element. The "hit" is therefore dependent upon the size of the array and
the amount of wasted work the default constructor must do.
But that aside, it is generally a recommended principle that a constructor fully initialize an object such that
it is ready to use. The above is somewhat akin to requiring a user to call an "Init" method on an object to
do post-construction initialization before any other methods can be called.