#include <iostream>
using namespace std;
class CType{
private:
int val;
public:
CType(): val(0){}
CType(int x): val(x){}
void setVal(int x){ val = x; }
~CType(){ cout << val << " is destructed." << endl;}
};
int main(){
// CType *t = new CType[10](10); // -1-
CType (*t)[10] = new CType[10][10]; // -2-
for(int i = 0; i < 10; ++i){
for(int j = 0; j < 10; ++j){
t[i][j].setVal(10 * i + j);
}
}
delete[] t;
return 0;
}
The above code is a sample I wrote to test new[][] and whether it is possible to initialize instances in dynamic array. My question is:
I intended to create an array of 10
CType
instances withval
initialized to 10. But this line cannot pass compilation. I have to add a default constructor with no parameter andCType *t = new CType[10]
. Is there any way to create an array of instances and invoke constructors with some parameters?I got puzzled by
new int[10][10]
which intuitively creates an 10x10 2D array. But I cannot find any official material defining the behavior ofnew int[][]
ornew int[][][]
etc. Why doesnew int[10][10]
have return typeint (*)[10]
rather thanint**
orint[10][10]
?
BTW, if I write CType (*t)[10] = new CType[10][10](10)
, I'll got a compilation error reading A.cpp:13:39: sorry, unimplemented: cannot initialize multi-dimensional array with initializer
. Funny, g++ says SORRY.
Update
I'm using g++. But I also tested the code on VS2010. It passed compilation and output the same result as it did in g++.
The variable t
in CType (*t)[10]
is a pointer which points to an array of 10 CType
instances, not an array of 10 CType
pointers. So t + 1
points to the place sizeof(CType) * 10
bytes away after t
.
The output of my code reveals that the destruct order of delete[] t
is 99 to 0. The last element of t + 9
is destructed first.