c++ - How do I decide if I should use a pointer or a regular variable? -


in c++ can declare field regular variable of type, instantiate in constructor, , use later:

private:    foo field; ...  a::a() {     // upd: instatiate field wrong ways (see comments)     field = fieldimpl(); } .... method(field); 

or alternatively can use pointer:

private:    foo* field; ...  a::a() {     field = new fieldimpl(); }  a::~a() {     delete field; }  ... method(*field); 

when declaring field, how decide if should use pointer or regular variable?

you might want use pointer if:

  • the referenced object can outlive parent.
  • because of size, want ensure referenced object on heap.
  • the pointer provided outside class.
  • null possible value.
  • the field can set dynamically different object.
  • the actual object type determined @ runtime. example, field might base-class pointer of number of subclasses.

you might want use smart pointer.

the last point above applies sample code. if field of type foo, , assign fieldimpl it, remains foo part of fieldimpl. referred slicing problem.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -