c++ - Dynamic vs non-dynamic class members -
in c++, ff have class needs hold member dynamically allocated , used pointer, or not, this:
class { type a; };
or
class { a(); ~a(); type* a; };
and in constructor:
a::a { = new type(); }
and destructor:
a::~a { delete a; }
are there advantages or disadvantages either one, aside dynamic 1 requiring more code? behave differently (aside pointer having dereferenced) or 1 slower other? 1 should use?
there several differences:
the size of every member must known when you're defining class. means must include
type
header, , can't use forward-declaration pointer member (since size of pointers known). has implications#include
clutter , compile times large projects.the memory data member part of enclosing class instance, allocated @ same time, in same place, other class members (whether on stack or heap). has implications data locality - having in same place potentially lead better cache utilization, etc. stack allocation tad faster heap allocation. declaring many huge object instances blow stack quicker.
the pointer type trickier manage - since doesn't automatically allocated or destroyed along class, need make sure yourself. becomes tricky multiple pointer members - if you're
new
ing of them in constructor, , halfway through process there's exception, destructor doesn't called , have memory leak. it's better assign pointer variables "smart pointer" container (likestd::auto_ptr
) immediately, way cleanup gets handled automatically (and don't need worrydelete
ing them in destructor, saving writing 1 @ all). also, time you're handling resources manually need worry copy constructors , assignment operators.
Comments
Post a Comment