diff --git a/gcc/cp/constexpr.cc b/gcc/cp/constexpr.cc index fb94f3cefcb..5e0fe93ebc0 100644 --- a/gcc/cp/constexpr.cc +++ b/gcc/cp/constexpr.cc @@ -4291,15 +4291,24 @@ cxx_eval_array_reference (const constexpr_ctx *ctx, tree t, else val = build_value_init (elem_type, tf_warning_or_error); - if (!SCALAR_TYPE_P (elem_type)) + /* Create a new constructor only if we don't already have a suitable one. */ + const bool new_ctor = (!SCALAR_TYPE_P (elem_type) + && (!ctx->ctor + || !same_type_ignoring_top_level_qualifiers_p + (elem_type, TREE_TYPE (ctx->ctor)))); + if (new_ctor) { new_ctx = *ctx; + /* We clear the object here. We used to replace it with T, but that + caused problems (101371, 108158); and anyway, T is the initializer, + not the target object. */ + new_ctx.object = NULL_TREE; new_ctx.ctor = build_constructor (elem_type, NULL); ctx = &new_ctx; } t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p, overflow_p); - if (!SCALAR_TYPE_P (elem_type) && t != ctx->ctor) + if (new_ctor && t != ctx->ctor) free_constructor (ctx->ctor); return t; } diff --git a/gcc/testsuite/g++.dg/cpp1y/constexpr-110382.C b/gcc/testsuite/g++.dg/cpp1y/constexpr-110382.C new file mode 100644 index 00000000000..317c5ecfcd5 --- /dev/null +++ b/gcc/testsuite/g++.dg/cpp1y/constexpr-110382.C @@ -0,0 +1,17 @@ +// PR c++/110382 +// { dg-do compile { target c++14 } } + +struct S { + double a = 0; +}; + +constexpr double +g () +{ + S arr[1]; + S s = arr[0]; + (void) arr[0]; + return s.a; +} + +int main() { return g (); }