【问题标题】:Is it possible to use brace initialization of a dynamic array using std::make_unique?是否可以使用 std::make_unique 对动态数组进行大括号初始化?
【发布时间】:2021-12-03 10:37:55
【问题描述】:

通常,我们可以使用大括号初始化动态分配来创建数组

int* arr = new int[5]{1,1,2,4,5};

但这是否可以使用智能指针,特别是使用 std::make_unique?我尝试了以下方法:

unique_ptr<int[]> arr(5) {1,1,2,4,5};
unique_ptr<int[]> arr = make_unique<int[]>(5){1,1,2,4,5};
unique_ptr<int[]> arr = make_unique<int[]>({1,1,2,4,5});

但无济于事,而且我认为这甚至可能无法使用智能指针。任何有关如何使用 大括号初始化 智能指针的建议将不胜感激。

是的,我知道std::vector,但希望有其他方法。

【问题讨论】:

    标签: c++ c++11 initialization smart-pointers unique-ptr


    【解决方案1】:

    这是否可以使用智能指针,特别是使用std::make_unique

    不,您不能使用 std::make_unique,因为它对数组有特殊的实现,并且仅限于未知范围。

    来自cppreference.com,对于未知界限std::make_unique 仅具有重载2

    (only for array types with unknown bound)
    template< class T >
    unique_ptr<T> make_unique( std::size_t size ); (2) (Since C++14)
    
    
    1. 构造一个给定动态大小的数组。数组元素是 value-initialized。仅当 T 是一个未知边界数组时,此重载才参与重载解析。

    这意味着,在您的情况下,它会创建给定大小的动态数组,并且整数将被初始化为0,并且不能传递初始化值。


    任何关于如何对智能指针使用大括号初始化的建议将不胜感激。

    你可以不用std::make_unique,比如:

    std::unique_ptr<int[]> arr{ new int[]{1, 1, 2, 4, 5} };
    

    或编写您自己的make_unique,它将创建您传递的元素类型的动态数组,并使用您传递的值进行初始化。

    #include <memory>
    #include <type_traits>  // std::common_type
    
    template<typename... Args>
    auto make_unique_init(Args&&... args)
    {
        using Type = std::common_type_t<Args...>;
        return std::unique_ptr<Type[]>(new Type[sizeof...(args)]{ std::forward<Args>(args)... });
    }
    

    现在你可以写了:

    std::unique_ptr<int[]> arr2 = make_unique_and_init(1, 1, 2, 4, 5);
    

    这是working example code

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 2016-12-20
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      相关资源
      最近更新 更多