【问题标题】:Is it possible to pass arguments to std::make_unique() when allocating an array?分配数组时是否可以将参数传递给 std::make_unique() ?
【发布时间】:2020-10-27 15:08:12
【问题描述】:

在下面的代码中,当使用std::make_unique() 分配demo[] 数组时,有什么方法可以将参数传递给demo 构造函数?

class demo{
public:
    int info;
    demo():info(-99){} // default value
    demo(int info): info(info){}
};
int main(){
    // ok below code creates default constructor, totally fine, no problem
    std::unique_ptr<demo> pt1 = std::make_unique<demo>();

    // and this line creates argument constructor, totally fine, no problem
    std::unique_ptr<demo> pt2 = std::make_unique<demo>(1800);

    // But now, look at this below line

    // it creates 5 object of demo class with default constructor

    std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5);

    // but I need here to pass second constructor argument, something like this : -

    //std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5, 200);
    return 0;
}

【问题讨论】:

  • 改用std::vector
  • 除此之外:从标题来看,我期待的是std::unique_ptr&lt;demo&gt;[],而不是std::unique_ptr&lt;demo[]&gt;

标签: c++ c++11 c++14


【解决方案1】:

std:::make_unique&lt;T[]&gt;() 不支持将参数传递给数组元素的构造函数。它总是只调用默认构造函数。您必须手动构建数组,例如:

std::unique_ptr<demo[]> pt3(new demo[5]{200,200,200,200,200});

如果您要创建大量元素,这显然不会有用。如果您不介意在构建它们后重新初始化它们,您可以这样做:

std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5);
std::fill_n(pt3.get(), 5, 200);

否则,请改用std::vector

std::vector<demo> pt3(5, 200);

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2020-09-14
    • 2012-12-26
    • 1970-01-01
    相关资源
    最近更新 更多