[libcxx-commits] [libcxx] [libc++] Ensure strong exception guarantee for forward_list::resize (PR #131025)

Peng Liu via libcxx-commits libcxx-commits at lists.llvm.org
Sun Jun 1 13:43:55 PDT 2025


================
@@ -1241,10 +1241,29 @@ void forward_list<_Tp, _Alloc>::resize(size_type __n) {
     erase_after(__p, __e);
   else {
     __n -= __sz;
+    __begin_node_pointer __r = __p.__get_begin();
     if (__n > 0) {
-      for (__begin_node_pointer __ptr = __p.__get_begin(); __n > 0; --__n, __ptr = __ptr->__next_as_begin()) {
-        __ptr->__next_ = this->__create_node(/* next = */ nullptr);
+      __node_pointer __first = this->__create_node(/* next = */ nullptr);
----------------
winner245 wrote:

> I wonder if we could use emplace_after instead with no _Args...? 

`emplace_after` only provide an implementation that allows insertion of a single element: `emplace_after(pos, ...args)`. However, what `resize(n)` actually need is something like `emplace_after(pos, n, ...args)` to insert `n` elements created in-place. 

> Or maybe we can add an internal version that gets called by both resize(n) and resize(n, value)?

I took this advice. I introduced an internal version `__insert_after(__p, __n, ...__args)`, which is now used by both `resize(n)` and `resize(n, v)`. 


https://github.com/llvm/llvm-project/pull/131025


More information about the libcxx-commits mailing list