c++ - vector related memory allocation question -
i encountering following bug.
- i have class
foo
. instances of class stored in std::vectorvec
ofclass b
. - in class foo, creating instance of class allocating memory using
new
, deleting object in~foo()
.
the code compiles, crash @ runtime. if disable delete my_a
desstructor of class foo
. code runs fine (but there going memory leak).
could please explain going wrong here , suggest fix?
thank you!
class a{ public: a(int val); ~a(){}; int val_a; }; a::a(int val){ val_a = val; }; class foo { public: foo(); ~foo(); void createa(); a* my_a; }; foo::foo(){ createa(); }; void foo::createa(){ my_a = new a(20); }; foo::~foo(){ delete my_a; }; class b { public: vector<foo> vec; void createfoo(); b(){}; ~b(){}; }; void b::createfoo(){ vec.push_back(foo()); }; int main(){ b b; int =0; (i = 0; < 5; ++){ std::cout<<"\n creating foo"; b.createfoo(); std::cout<<"\n foo created"; } std::cout<<"\ndone foo creation"; std::cout << "\npress return continue..."; std::cin.get(); return 0; }
you need implement copy constructor , assignment operator foo. whenever find need destructor, alnmost need these 2 well. used in many places, putting objects standard library containers.
the copy constructor should this:
foo :: foo( const foo & f ) : my_a( new a( * f.my_a ) ) { }
and assignment operator:
foo & foo :: operator=( const foo & f ) { delete my_a; my_a = new a( * f.my_a ); return * this; }
or better still, don't create instance in foo class dynamically:
class foo { public: foo(); ~foo(); void createa(); my_a; }; foo::foo() : my_a( 20 ) { };
Comments
Post a Comment