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:

  1. 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.

  2. 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.

  3. 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 newing 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 (like std::auto_ptr) immediately, way cleanup gets handled automatically (and don't need worry deleteing them in destructor, saving writing 1 @ all). also, time you're handling resources manually need worry copy constructors , assignment operators.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -