Creating shared_ptr from raw pointer

后端 未结 2 720
北荒
北荒 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:37

    You need to make sure you don't initialize both shared_ptr objects with the same raw pointer, or it will be deleted twice. A better (but still bad) way to do it:

    classA* raw_ptr = new classA;
    shared_ptr my_ptr(raw_ptr);
    
    // or shared_ptr my_ptr = raw_ptr;
    
    // ...
    
    shared_ptr other_ptr(my_ptr);
    // or shared_ptr other_ptr = my_ptr;
    // WRONG: shared_ptr other_ptr(raw_ptr);
    // ALSO WRONG: shared_ptr other_ptr = raw_ptr;
    

    WARNING: the above code shows bad practice! raw_ptr simply should not exist as a variable. If you directly initialize your smart pointers with the result of new, you reduce your risk of accidentally initializing other smart pointers incorrectly. What you should do is:

    shared_ptr my_ptr(new classA);
    
    shared_ptr other_ptr(my_ptr);
    

    What's nice is that the code is more concise as well.

    EDIT

    I should probably elaborate on how it would work with a map. If you had a raw pointer and two maps, you could do something similar to what I showed above.

    unordered_map > my_map;
    unordered_map > that_guys_map;
    
    shared_ptr my_ptr(new classA);
    
    my_map.insert(make_pair("oi", my_ptr));
    that_guys_map.insert(make_pair("oi", my_ptr));
    // or my_map["oi"].reset(my_ptr);
    // or my_map["oi"] = my_ptr;
    // so many choices!
    

提交回复
热议问题