release dynamic memory for pointer member in c++ -
i have class:
class { a(); ////////something class };
then have class:
class b { public: b(); a* member_a; }; b::b() { this->member_a = new a(); }
what want this:
main() { vector<b> vec_b; int num=1; while(some_condition) { (int i=0; i<num; i++) { vec_b.pushback(b()); } ////////do vec_b; num++; } }
i know facing memory leak issue because of new a()
in constructor of class b
. trying release memory after each while
loop, means recycle memory has been taken vec_b
, objects of class b in vector, important release memory taken class-a-objects. thank much!
that seems should job of b
's destructor
b::~b() { delete member_a; }
if have access c++11 or later, prefer std::unique_ptr
deallocation free
class b { public: b(); std::unique_ptr<a> member_a; }; b::b() { member_a = std::make_unique<a>(); }
Comments
Post a Comment