1

I'm trying to understand the exception safety of the template <class U> void shared_ptr::reset (U* p); function. In the documentation I found this:

Additionally, a call to this function has the same side effects as if shared_ptr's destructor was called before its value changed (including the deletion of the managed object if this shared_ptr was unique).

So, we can assume that destructor doesn't throw. But what if the operator new throws? What state of the shared_ptr will we have then? Does it remain unchanged?

T.C.
  • 133,968
  • 17
  • 288
  • 421
stella
  • 2,546
  • 2
  • 18
  • 33
  • [This](http://en.cppreference.com/w/cpp/memory/shared_ptr/reset) is a little more descriptive: " std::bad_alloc if required additional memory could not be obtained. May throw implementation-defined exception for other errors. delete ptr is called if an exception occurs." – AndyG Nov 17 '15 at 04:07
  • Which `operator new`? The one called to allocate the new control block? – T.C. Nov 17 '15 at 04:08
  • As a small sidenote preferr http://cppreference.com over cplusplus.com. [Cplusplus.com has many small mistakes and some bad examples.](http://stackoverflow.com/questions/6520052/whats-wrong-with-cplusplus-com) – RedX Nov 17 '15 at 04:12

2 Answers2

2

Per [util.smartptr.shared.mod], all four overloads of shared_ptr::reset(stuff) are exactly equivalent to

shared_ptr(stuff).swap(*this)

If constructing shared_ptr(stuff) throws (e.g., if allocating the new control block (or whatever equivalent mechanism used by the implementation) throws), then *this is unaffected because you never get to the swap, and any pointer passed in stuff is deleted appropriately (because that's guaranteed by shared_ptr's constructor).

swap itself is nothrow, and so is destroying the temporary shared_ptr after the swap.

T.C.
  • 133,968
  • 17
  • 288
  • 421
1

The function takes a pointer. That means the new would have to be done prior to execution entering the function. Inside the function I assume only a pointer and some of integer type are being assigned and those don't throw.

Anon Mail
  • 4,660
  • 1
  • 18
  • 21