From e6a1cc363c54e5bcbf0381cd3fade6ef86c33f9d Mon Sep 17 00:00:00 2001 From: Herb Sutter Date: Fri, 20 Oct 2023 15:07:45 -0700 Subject: [PATCH] Make `new` use list initialization if available This enables uses like `new>(1, 2, 3, 4, 5)` which didn't work before (not even with P0960) See #740 Note: I chose "use list init if available, else fall back to non-list init" instead of "use paren init if available, else fall back to list init" so that we would get consistent results for initializing a `new>` with `(10)`, `(10, 20)`, `(10, 20, 30)`, etc. (i.e., no surprise for `(10, 20)`) --- include/cpp2util.h | 16 ++++++++++++++-- .../test-results/msvc-2022/MSVC-version.output | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/include/cpp2util.h b/include/cpp2util.h index a089e59cb..354093ea9 100644 --- a/include/cpp2util.h +++ b/include/cpp2util.h @@ -556,14 +556,26 @@ auto Typeid() -> decltype(auto) { struct { template [[nodiscard]] auto cpp2_new(auto&& ...args) const -> std::unique_ptr { - return std::make_unique(CPP2_FORWARD(args)...); + if constexpr (requires { T{CPP2_FORWARD(args)...}; }) { + // This is because apparently make_unique can't deal with list + // initialization of aggregates, even after P0960 + return std::unique_ptr( new T{CPP2_FORWARD(args)...} ); + } + else { + return std::make_unique(CPP2_FORWARD(args)...); + } } } inline unique; [[maybe_unused]] struct { template [[nodiscard]] auto cpp2_new(auto&& ...args) const -> std::shared_ptr { - return std::make_shared(CPP2_FORWARD(args)...); + if constexpr (requires { T{CPP2_FORWARD(args)...}; }) { + return unique.cpp2_new(CPP2_FORWARD(args)...); + } + else { + return std::make_shared(CPP2_FORWARD(args)...); + } } } inline shared; diff --git a/regression-tests/test-results/msvc-2022/MSVC-version.output b/regression-tests/test-results/msvc-2022/MSVC-version.output index bd44f14bb..1559c12b5 100644 --- a/regression-tests/test-results/msvc-2022/MSVC-version.output +++ b/regression-tests/test-results/msvc-2022/MSVC-version.output @@ -1,3 +1,3 @@ -Microsoft (R) C/C++ Optimizing Compiler Version 19.37.32824 for x86 +Microsoft (R) C/C++ Optimizing Compiler Version 19.37.32825 for x86 Copyright (C) Microsoft Corporation. All rights reserved.