简体   繁体   English

分配数组时是否可以将 arguments 传递给 std::make_unique() ?

[英]Is it possible to pass arguments to std::make_unique() when allocating an array?

In the code below, is there any way that I can pass an argument to the demo constructor when using std::make_unique() to allocate a demo[] array?在下面的代码中,有什么方法可以在使用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:::make_unique<T[]>() does not support passing arguments to the constructor of array elements. std:::make_unique<T[]>()不支持将 arguments 传递给数组元素的构造函数。 It always invokes the default constructor only.它总是只调用默认构造函数。 You would have to construct the array manually, eg:您将不得不手动构建数组,例如:

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

Which is obviously not going to be useful if you have a large number of elements to create.如果您要创建大量元素,这显然不会有用。 You could do something like this instead, if you don't mind re-initializing them after constructing them:如果你不介意在构造它们之后重新初始化它们,你可以做这样的事情:

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

Otherwise, just use std::vector instead:否则,只需使用std::vector代替:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM