Updates:
The link above and the answers below didn't answer WHY this feature is not standardized. That is just what makes me wonder. Please consider the performance issue between std::vector<A> arr(8, 7);
and new A[8](7);
:
If we use std::vector<A> arr(8, 7);
it may (not must) be implemented as follows:
this->internal_buf = new A[8]; // Call default constructor A() 8 times!
for (auto i = 0; i < 8; ++i)
{
this->internal_buf[i] = A(7); // Call constructor A(7) 8 times AGAIN!!!
}
If C++ supports new A[8](7);
It can be implemented as follows:
A* arr = (A*)malloc(sizeof(A) * 8 + extra_size);
for (auto i = 0; i < 8; ++i)
{
new (&arr[i]) A(7); // Call constructor A(7) 8 times ONLY.
}
Compare the two methods, it is obvious that new A[8](7);
is FASTER than std::vector<A> arr(8, 7);
Besides, I also feel new A[8](7);
is more succinct and more expressive than std::vector<A> arr(8, 7);
Anyway, I think C++ should give programmers another alternative tool such as this feature. Because one of the C++ philosophies is "Give you as many tools as possible, but you don't have to pay for what you don't need."
The following is the original post:
struct A
{
int n;
A() : n() {}
A(int n) : n(n) {}
};
int main()
{
new A[8]; // OK
new A[8](); // OK
new A[8](7); // Error
}
Why can I not specify the constructor when newing an array?
Why does the C++ standard not support such a handy feature? What's the rationale?