https://gcc.gnu.org/g:ce268ca2a923f8f35cc9dd5a7d0468a3980f129f
commit r15-7206-gce268ca2a923f8f35cc9dd5a7d0468a3980f129f Author: Jakub Jelinek <ja...@redhat.com> Date: Sat Jan 25 10:15:24 2025 +0100 c++: Only destruct elts of array for new expression if exception is thrown during the initialization [PR117827] The following testcase r12-6328, because the elements of the array are destructed twice, once when the callee encounters delete[] p; and then second time when the exception is thrown. The array elts should be only destructed if exception is thrown from one of the constructors during the build_vec_init emitted code in case of new expressions, but when the new expression completes, it is IMO responsibility of user code to delete[] it when it is no longer needed. So, the following patch uses the cleanup_flags argument to build_vec_init to get notified of the flags that need to be changed when the expression is complete and build_disable_temp_cleanup to do the changes. 2025-01-25 Jakub Jelinek <ja...@redhat.com> PR c++/117827 * init.cc (build_new_1): Pass address of a make_tree_vector () initialized gc tree vector to build_vec_init and append build_disable_temp_cleanup to init_expr from it. * g++.dg/init/array66.C: New test. Diff: --- gcc/cp/init.cc | 17 ++++++++++++++++- gcc/testsuite/g++.dg/init/array66.C | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/gcc/cp/init.cc b/gcc/cp/init.cc index f2c462419af0..3ab7f96335c9 100644 --- a/gcc/cp/init.cc +++ b/gcc/cp/init.cc @@ -3709,6 +3709,11 @@ build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts, error ("parenthesized initializer in array new"); return error_mark_node; } + + /* Collect flags for disabling subobject cleanups once the complete + object is fully constructed. */ + vec<tree, va_gc> *flags = make_tree_vector (); + init_expr = build_vec_init (data_addr, cp_build_binary_op (input_location, @@ -3718,7 +3723,17 @@ build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts, vecinit, explicit_value_init_p, /*from_array=*/0, - complain); + complain, + &flags); + + for (tree f : flags) + { + tree cl = build_disable_temp_cleanup (f); + cl = convert_to_void (cl, ICV_STATEMENT, complain); + init_expr = build2 (COMPOUND_EXPR, void_type_node, + init_expr, cl); + } + release_tree_vector (flags); } else { diff --git a/gcc/testsuite/g++.dg/init/array66.C b/gcc/testsuite/g++.dg/init/array66.C new file mode 100644 index 000000000000..ca38df815dea --- /dev/null +++ b/gcc/testsuite/g++.dg/init/array66.C @@ -0,0 +1,33 @@ +// PR c++/117827 +// { dg-do run { target c++11 } } + +struct C { + int c; + static int d, e; + C () : c (0) { ++d; } + C (const C &) = delete; + C &operator= (const C &) = delete; + ~C () { ++e; } +}; +int C::d, C::e; + +C * +foo (C *p) +{ + delete[] p; + throw 1; +} + +int +main () +{ + try + { + foo (new C[1] {}); + } + catch (...) + { + } + if (C::d != C::e) + __builtin_abort (); +}