When should I use raw pointers over smart pointers?

后端 未结 8 1415
礼貌的吻别
礼貌的吻别 2020-11-28 02:49

After reading this answer, it looks like it is a best practice to use smart pointers as much as possible, and to reduce the usage of \"normal\"/raw pointers to minimum.

8条回答
  •  渐次进展
    2020-11-28 02:56

    The use of smart pointers is always recommended because they clearly document the ownership.

    What we really miss, however, is a "blank" smart pointer, one that does not imply any notion of ownership.

    template 
    class ptr // thanks to Martinho for the name suggestion :)
    {
    public:
      ptr(T* p): _p(p) {}
      template  ptr(U* p): _p(p) {}
      template  ptr(SP const& sp): _p(sp.get()) {}
    
      T& operator*() const { assert(_p); return *_p; }
      T* operator->() const { assert(_p); return _p; }
    
    private:
      T* _p;
    }; // class ptr
    

    This is, indeed, the simplest version of any smart pointer that may exist: a type that documents that it does not own the resource it points too.

提交回复
热议问题