boost shared_ptr: difference between operator= and reset?

前端 未结 4 1361
眼角桃花
眼角桃花 2021-02-13 22:55

Are there any differences between the two pieces of code below? Is any of them preferable to the other?

operator=

boost::shared_ptr&         


        
4条回答
  •  独厮守ぢ
    2021-02-13 23:12

    operator= assigns a shared_ptr to a shared_ptr, while reset makes a shared_ptr take ownership of a pointer. So, basically there is no difference between the examples you have posted. That said, you should prefer neither of them and just use make_shared:

    foo = boost::make_shared();
    

    Also, if possible, you can prevent having to declare a shared_ptr without initialization by wrapping the try-catch block in a separate function that simply returns a shared_ptr to the newly created object:

    boost::shared_ptr createBlah() {
        try {
            // do stuff
            return newBlah;
        }
        catch ...
    }
    

提交回复
热议问题