When to use pointers and when not to?

后端 未结 5 1291
滥情空心
滥情空心 2020-12-02 08:21

I\'m used to doing Java programming, where you never really have to think about pointers when programming. However, at the moment I\'m writing a program in C++. When making

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 08:31

    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

提交回复
热议问题