Alex Rivera | Logout

c++: when to use pointers?

Asked 2009-03-18T12:49:05.817
16

After reading some tutorials I came to the conclusion that one should always use pointers for objects. But I have also seen a few exceptions while reading some QT tutorials (http://zetcode.com/gui/qt4/painting/) where QPaint object is created on the stack. So now I am confused. When should I use pointers?

Edit
Report

2 Answers

21

Main reasons for using pointers:

  1. control object lifetime;
  2. can't use references (e.g. you want to store something non-copyable in vector);
  3. you should pass pointer to some third party function;
  4. maybe some optimization reasons, but I'm not sure.
answered 2009-03-18T12:56:06.720
0

Use pointers when you don't want your object to be destroyed when the stack frame is emptied.

Use references for passing parameters where possible.

answered 2009-03-18T12:57:39.430

Your Answer