Does copy-and-swap still give the strong exception guarantee in C++11? -
Does copy-and-swap still give the strong exception guarantee in C++11? -
the copy-and-swap idiom said provide strong exception guarantee. in c++11, std::swap uses move operations.
consider next code:
class myclass { aclass x; canthrowifmoved throwingobject; myclass(myclass&& other) noexcept x(std::move(other.x)), throwingobject(std::move(other.throwingobject)) { } friend void swap(myclass& first, myclass& second) noexcept { using std::swap; swap(first.x, other.x); swap(first.throwingobject, other.throwingobject); } myclass& operator=(myclass other) noexcept { swap(*this, other); homecoming *this; } }; if throwingobject throws during swap, strong exception guarantee broken.
the noexcept keywords don't enforce during compile time. throwingobject can still throw, difference programme violently terminate. don't think crashing entire application when exception occurs counts strong exception guarantee.
does mean copy-and-swap no longer enforces strong exception guarantee in c++11?
similar questions
this question similar, it's targeted @ using standard library. i'm interested in issue means strong exception guarantee of copy-and-swap idiom.
this question discusses how utilize noexcept in copy-and-swap idiom, discusses copy. not swap, problem seems be.
instead of straight invoking swap in swap fellow member method, utilize helper function template, checks @ compile time noexcept guarantee:
friend void swap(myclass& first, myclass& second) noexcept { util::swap_noexcept(first.x, other.x); util::swap_noexcept(first.throwingobject, other.throwingobject); } namespace util { template <typename ...args> void swap_noexcept(args&&... args) noexcept { using std::swap; static_assert(noexcept(swap(std::forward<args>(args)...)), "requires noexcept"); swap(std::forward<args>(args)...); } } exception c++11 copy-and-swap
Comments
Post a Comment