It is not normal. You copy objects to uninitialized memory without causing the correct copy semantics.
While you work only with POD, everything is in order. However, when working with objects that are not PODs (like yours A), you need to take precautions.
, operator new . Alexandre , , ++ operator new, :
#include <cstdlib>
#include <iostream>
template<typename T>
void* operator new [] (size_t size, T value) {
T* p = (T*) std::malloc(size);
for(int i = size / sizeof(T) - 1; i >= 0; i--)
new(p + i) T(value);
return p;
}
struct A {
int x;
A(int x) : x(x) { std::cout << "int ctor\n"; }
A() : x(0) { std::cout << "default ctor\n"; }
A(const A& other) : x(other.x) { std::cout << "copy ctor\n"; }
};
int main() {
A *p = new(A(42)) A[2];
for (unsigned i = 0; i < 2; ++i)
std::cout << p[i].x << std::endl;
}
:
int ctor
copy ctor
copy ctor
default ctor
default ctor
0
0
... .