c++ - Object getting deconstructed when out of scope -
i have class , has array of objects instance variable. each object internally contains int
, struct
. somehow object gets deconstructed.
i.e.
class allinput { public: int numproducts; product * products; public: allinput(int _numproducts, product * _products); }; class product { public: int sellingprice; //ri struct demanddistribution observationdemand; //c2i public: product( lucydecimal _sellingprice, //ri lucydecimal _costpriceassmbly); };
and have function creates it:
allinput* in1() { struct demanddistribution * _observationdemand1 = (demanddistribution*) malloc(sizeof(demanddistribution)); // set values product * product1 = new product(165,_observationdemand1); //initialize product2, product3, product4 product products[4] = { *product1, * product2, *product3, *product4}; allinput* = new allinput(4, products); return all; }
when allinput* in = in1()
. executed, see each product among 4 gets deconstructed (thanks print statement in deconstructor of product). missing?
ps: need use pointer , not references because need next copy cuda memory.
you declared product products[4]
on stack, released when outscoping (leaving function)
product products[4] = { *product1, * product2, *product3, *product4}; allinput* = new allinput(4, products);
when constructing dymamicly allocated allinput
, if don't copy products internal members of allinputs
, when leaving function in1
, products
freed , pointer saved in allinput
point junk.
so create dynamic allocation products
too, or copy data (the array of pointers) in allinput
.
Comments
Post a Comment