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

H.D*_*Das 5 c++ c++11 c++14

在下面的代码中,有什么方法可以demo在使用std::make_unique()分配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;
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 3

std:::make_unique<T[]>()不支持将参数传递给数组元素的构造函数。它始终只调用默认构造函数。您必须手动构造数组,例如:

std::unique_ptr<demo[]> pt3(new demo[5]{200,200,200,200,200});
Run Code Online (Sandbox Code Playgroud)

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

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

否则,只需使用std::vector

std::vector<demo> pt3(5, 200);
Run Code Online (Sandbox Code Playgroud)