For a class without default constructor, operator new and placement new can be used to declare an array of such class.
When I read the code in More Effective C++, I found the code as below(I modified some part).....
My question is, why [] after the operator new is needed?
I test it without it, it still works. Can any body explain that?
class A {
public:
int i;
A(int i):i(i) {}
};
int main()
{
void *rawMemory = operator new[] (10 * sizeof(A)); // Why [] needed here?
A *p = static_cast<A*>(rawMemory);
for(int i = 0 ; i < 10 ; i++ ) {
new(&p[i])A(i);
}
for(int i = 0 ; i < 10 ; i++ ) {
cout<<p[i].i<<endl;
}
for(int i = 0 ; i < 10 ; i++ ) {
p[i].~A();
}
return 0;
}