c++ - initializing pre-allocated struct instances within a loop -
i want allocate memory number of instances of structure, using malloc(). then, want initialize each instance within loop. but, each iteration, observ constructor, , destructor after, called... why? more suprising me fact each of instance exists after loop despite of call of destructor... , instances initialized same values! i'm definitively missing important... grateful if can me because now, can't explain happen. here c++ code :
struct mystruct{ int* a; int* b; mystruct(int x, int y) { std::cout << "the constructor called" << std::endl; = (int*)malloc(x*sizeof(int)); b = (int*)malloc(y*sizeof(float)); } ~mystruct() { std::cout << "the destructor 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 " << << " :" << 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 called
the destructor called
the constructor called
the destructor called
the constructor called
the destructor called
instance 0 : 1608524712 4277075694
instance 1 : 1608524712 4277075694
instance 2 : 1608524712 4277075694
press key continue . . .
best regards
in expression
*(s+i) = mystruct(1,2)
what happens create temporary instance of structure (the mystruct(1,2)
part) copy instance s[i]
. copy shallow, , pointers copied , no new data allocated or copied. after expression done temporary instance not needed anymore , destructed.
this destruction of course cause freeing of data members, , pointers in structure in array (the copy) no longer valid, , accessing them undefined behavior. also, don't initialize allocated memory anything, memory contain whatever in there before allocation , contents seem random.
i suggest read std::vector
, std::shared_ptr
, , importantly the rule of three.
Comments
Post a Comment