How to safely delete multiple pointers

前端 未结 8 1906
無奈伤痛
無奈伤痛 2021-01-03 02:06

I have got some code which uses a lot of pointers pointing to the same address. Given a equivalent simple example:

int *p =  new int(1);
int *q = p;
int *r =         


        
8条回答
  •  心在旅途
    2021-01-03 02:21

    Your tool is shared_ptr of the boost library. Take a look at the documentation: http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/shared_ptr.htm

    Example:

    void func() {
      boost::shared_ptr p(new int(10));
      boost::shared_ptr q(p);
      boost::shared_ptr r(q);
    
      // will be destructed correctly when they go out of scope.
    }
    

提交回复
热议问题