operator new for array of class without default constructor......
Posted
by skydoor
on Stack Overflow
See other posts from Stack Overflow
or by skydoor
Published on 2010-03-26T02:35:18Z
Indexed on
2010/03/26
2:43 UTC
Read the original article
Hit count: 506
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;
}
© Stack Overflow or respective owner