【问题标题】:Create a unique_ptr to an array with type double in c++在 C++ 中为 double 类型的数组创建一个 unique_ptr
【发布时间】:2020-07-06 08:21:12
【问题描述】:

我正在为包含以下内容的类编写构造函数:

// my_class.hpp
private:
    std::unique_ptr<double[]> my_list;

我在尝试初始化 my_list

时遇到了一些问题
my_class::my_class(const int new_size, const double new_values){
    // creating an array with new_values as initial value.
    auto size = static_cast<const size_t>(new_size);
    my_list = std::make_unique<double[]>(size);          // <-- Error
    for (size_t i = 0; i < size; i++){
        my_list[i] = new_values;
    }
}

错误消息:“不要声明 C 样式数组,使用 std::array 代替 [modernize-avoid-c-arrays,-warnings-as-errors]”

我尝试了以下方法:

    my_list = std::make_unique<std::array<double>>(size);    // <-- Error
    // Error Message: "too few template arguments for class template 'array' [clang-diagnostic-error]"

    my_list = std::make_unique<std::array<double,size>>(size);    // <-- Error
    // Error Message: "non-type template argument is not a constant expression [clang-diagnostic-error]"

我该如何解决这个问题,还有什么方法可以在不循环遍历每个元素的情况下初始化这样的数组?

【问题讨论】:

  • 一个 std::array 是一个固定大小的数组。你可能想要一个 std::vector。阅读这两个选项并自行决定。
  • 当我们有std::vector&lt;T&gt; 时,我从未真正见过std::unique_ptr&lt;T[]&gt; 的用例。如果需要所有权语义,那么std::unique_ptr&lt;std::vector&lt;T&gt;&gt; 可能会更好(并且是指向容器的指针的一个很好的用例,这通常不常见)。
  • 你在哪里声明magnitudes
  • @Someprogrammerdude 当你的遗留代码给你一个你可以拥有的指针并且你想避免复制时,它会很有用。不过,我没有看到“从头开始”创建一个案例。
  • 您的错误不是来自标准 c++ 并且可能不正确。看起来它希望您在代码中仅使用 vectors。

标签: c++ arrays unique-ptr


【解决方案1】:

我该如何解决这个问题

std::unique_ptr&lt;double[]&gt; 切换为std::vector&lt;double&gt;

有没有什么方法可以在不遍历每个元素的情况下初始化这样的数组?

my_class::my_class(std::size_t new_size, double new_values) 
: my_list(new_size, new_values) 
{}

【讨论】:

    【解决方案2】:

    有两种方法可以解决此问题。

    1. 保留您的std::unique_ptr&lt;double[]&gt;,您不需要更改其余代码,但需要替换这两行
        auto size = static_cast<const size_t>(new_size);
        my_list = std::make_unique<double[]>(size);          // <-- Error
    

    用这个:

        my_list = std::make_unique<double[]>(new_size);  // allocates new_size of doubles
    
    1. 正如 Caleth 指出的,您可以将数据成员 my_list 的类型从 std::unique_ptr&lt;double[]&gt; 更改为 std::vector&lt;double&gt;,但随后您需要更改所有访问 my_list 的位置。

    我该如何解决这个问题,还有什么方法可以在不循环遍历每个元素的情况下初始化这样的数组?

    如果您将 my_list 保留为 unique_ptr,那么您可以使用 std::fill_n(my_list.get(), new_size, new_values) 来初始化您的数组。

    【讨论】:

    • 我正在使用解决方案 1,但最终得到不同的错误消息“没有匹配的函数用于调用 make_unique”
    • 对不起,语法错误,应该是std::make_unique&lt;double[]&gt;(new_size);
    • 解决方案 1 并不是真正需要的。他的做法是多余的,但却是有效的。
    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2017-05-26
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多