C++ - when should I use a pointer member in a class

后端 未结 4 2180
庸人自扰
庸人自扰 2020-12-07 17:02

One of the thing that has been confusing for me while learning C++ (and Direct3D, but that some time ago) is when you should use a pointer member in a class. For example, I

4条回答
  •  没有蜡笔的小新
    2020-12-07 17:45

    A pointer has following advantages:

    a) You can do a lazy initialization, that means to init / create the object only short before the first real usage.

    b) The design: if you use pointers for members of an external class type, you can place a forward declaration above your class and thus don't need to include the headers of that types in your header - instead of that you include the third party headers in your .cpp - that has the advantage to reduce the compile time and prevents side effects by including too many other headers.

    class ExtCamera;  // forward declaration to external class type in "ExtCamera.h"
    
    class MyCamera {
    public: 
      MyCamera() : m_pCamera(0) { }
    
      void init(const ExtCamera &cam);
    
    private:
       ExtCamera  *m_pCamera;   // do not use it in inline code inside header!
    };
    

    c) A pointer can be deleted anytime - so you have more control about the livetime and can re-create an object - for example in case of a failure.

提交回复
热议问题