Can I select a constructor to use with new?

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.

Enligthen me, please.
Last edited on
I asked a similar question a while back.

It can't be done. Dynamically allocating arrays with new[] means you have to use the default ctor.
closed account (1yR4jE8b)
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?
Nothing prevents it, but it is a performance hit.
closed account (1yR4jE8b)
Unless you are initializing objects that use 200mB of memory, 2000 times in a loop I don't see why this performance hit is actually a "hit".
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.
You can minimize that "hit" by using operator new, to allocate the space, then looping through the array and using the constructor directly.

You could use things like std::for_each, or even write your own little template, to do this kind of thing.

Good luck!
Topic archived. No new replies allowed.