I want to allocate memory for a certain number of instances of a certain structure, using malloc(). Then, i want to initialize each instance within a loop. But, for each iteration, i observ that the constructor, and the destructor just after, are called... why? More suprising for me is the fact that each of my instance exists after the loop despite of the call of the destructor... and my instances are initialized with same values! I'm definitively missing something important... I would be grateful if someone can help me because for now, i can't explain what happen. Here is my C++ code :
struct myStruct{
int* a;
int* b;
myStruct(int x, int y)
{
std::cout << "the constructor is called" << std::endl;
a = (int*)malloc(x*sizeof(int));
b = (int*)malloc(y*sizeof(float));
}
~myStruct()
{
std::cout << "the destructor is called" << std::endl;
delete[] a;
delete[] b;
} };
int main(int argc, char** argv){
int Nb = 3;
myStruct *S = (myStruct*)malloc(Nb*sizeof(myStruct));
for(int i=0 ; i<Nb ; i++)
{
*(S+i) = myStruct(1,2);
}
std::cout << std::endl;
for(int i=0 ; i<Nb ; i++)
{
std::cout << "instance " << i << " :" << std::endl;
std::cout << (unsigned int)(*(S+i)->a) << std::endl;
std::cout << (unsigned int)(*(S+i)->b) << std::endl << std::endl;
}
system("PAUSE");}
My command window display :
the constructor is called
the destructor is called
the constructor is called
the destructor is called
the constructor is called
the destructor is called
instance 0 : 1608524712 4277075694
instance 1 : 1608524712 4277075694
instance 2 : 1608524712 4277075694
Press any key to continue . . .
Best Regards