Start by avoiding pointers.
Use them when:
- You want to use the Pimpl idiom, or an abstract factory.
- The
Bar
instance is actually managed by some other part of your program, whereas the Foo
class just needs to be able to access it.
- You want to postpone the construction of the
Bar
object (i.e., you want to create it after constructing Foo
).
- In your business logic, the
Bar
object may not exist at all; you would use null
also in Java. However, check out boost::optional as well.
Bar
is actually a base class, and you need the instance to be polymorphic.
- You happen to be using a toolkit that prefers to present GUI widgets as pointers. Examples could include (but are certainly not limited to) wxWidgets and GLUI.
In any of these cases (*), start by using a smart pointer, such as boost::shared_ptr. Otherwise, you are likely to forget to deallocate the memory, sooner or later. Once you know what you are doing, consider case-by-case what pointer type is best.
(*) any case – except, probably, the bullet regarding GUI widgets; in this case, your toolkit would most probably manage the resources for you as well
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…