is it better to use shared_ptr.reset or operator =?

后端 未结 2 687
再見小時候
再見小時候 2020-12-08 09:50

I\'m trying to wrap my head around the new idioms for C++11.

It seems that with shared_ptr at least, there is a substantive difference between using new T()

2条回答
  •  感情败类
    2020-12-08 10:13

    Correct, reset(new T...) suffers all the issues of shared_ptr(new T...); it will result in double allocation and also is non-exception-safe (there's not much chance of a leak, unless bad_alloc happens within reset).

    reset is documented as equivalent to shared_ptr(ptr).swap(*this), so you could also write:

    make_shared(args...).swap(mysharedptr);
    

    Assignment from make_shared is almost equivalent, the only difference being the relative order of the deletion of the old T and the destruction of the temporary shared_ptr, which is not observable.

提交回复
热议问题