https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109305
--- Comment #8 from Jonathan Wakely <redi at gcc dot gnu.org> --- (In reply to Jonathan Wakely from comment #5) > Removing it would make the code less efficient and more complex. In fact, I don't even see how it would be possible, except by making *another* copy, e.g. --- a/libstdc++-v3/include/bits/basic_string.h +++ b/libstdc++-v3/include/bits/basic_string.h @@ -1588,20 +1588,33 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11 _M_destroy(_M_allocated_capacity); _M_data(_M_use_local_data()); _M_set_length(0); + std::__alloc_on_copy(_M_get_allocator(), + __str._M_get_allocator()); } else { + auto __backup_alloc = _M_get_allocator(); + std::__alloc_on_copy(_M_get_allocator(), + __str._M_get_allocator()); const auto __len = __str.size(); - auto __alloc = __str._M_get_allocator(); - // If this allocation throws there are no effects: - auto __ptr = _Alloc_traits::allocate(__alloc, __len + 1); - _M_destroy(_M_allocated_capacity); + pointer __ptr; + __try { + __ptr = _Alloc_traits::allocate(_M_get_allocator(), + __len + 1); + } __catch (...) { + std::__alloc_on_copy(_M_get_allocator(), __backup_alloc); + __throw_exception_again; + } + _Alloc_traits::deallocate(__backup_alloc, _M_data(), + _M_allocated_capacity + 1); _M_data(__ptr); _M_capacity(__len); _M_set_length(__len); } } - std::__alloc_on_copy(_M_get_allocator(), __str._M_get_allocator()); + else + std::__alloc_on_copy(_M_get_allocator(), + __str._M_get_allocator()); } #endif this->_M_assign(__str); This makes the code much worse, and slower, and still has a copy (the __backup_alloc) variable.