Creating shared_ptr from raw pointer

后端 未结 2 717
北荒
北荒 2020-12-07 21:57

I have a pointer to an object. I would like to store it in two containers which both have the ownership. So I think I would be good to make it a shared_ptr of C++0x. How cou

2条回答
  •  [愿得一人]
    2020-12-07 22:36

    You can use a variety of ways, but reset() would be good:

    map1[ID].reset(obj);
    

    And to address the issue of having two maps refer to the same shared_ptr, we can have:

    map2[ID] = map1[ID];
    

    Note that the trick in general to avoid a double delete is to try to avoid raw pointers at all. Hence avoid:

    classA* obj = new classA();
    map1[ID].reset(obj);
    

    but instead put the new heap object straight into a shared_ptr.

提交回复
热议问题