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

Viewed 527

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?

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;
}
1 Answers

std:::make_unique<T[]>() does not support passing arguments to the constructor of array elements. 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<demo> pt3(5, 200);
Related