.Reset () Method of Normal Smart Pointers

It seems to me that the reset method in boost scroll_ptr and shared_ptr leads to an incorrect order of construction and destruction:

boost::scoped_ptr<Component> component(GetDefaultComponent());
component.reset(new BetterComponent); // 1. Creation of the new object
                                      // 2. Destruction of the old object

This is the wrong IMO order.

You can first call the reset method with no arguments, and then set a new pointer. However, this seems like a workaround for me. (And this “workaround” means that something is wrong.)

I am convinced that activists are very smart. Thus, there should be a rationale for the current approach.

Does anyone know more?

+3
source share
2 answers

This is an absolutely correct order. What happens if new BetterComponentthrows away? Oops This is the same order in which everything happens, it is called copy and replace, and this is the best way to go.

, , .

+13

( - ):

template<typename T, typename Pointer, typename... U>
void
emplace_reset(Pointer& pointer, U&&... u)
{
    pointer.reset();
    pointer.reset(new T(std::forward<U>(u)...));
}
// use as: emplace_reset<BetterComponent>(component);

, reset , . , , .

, , ( - /), , , , : , . reset .

+1

All Articles