Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of smart pointers to a class with no default constructor

I'm referring to the question , Can we create an array of std::unique_ptr to a class which has deleted default constructor as below, How to pass the string argument.

#include <iostream>  
#include <string>  
#include <memory>

using namespace std;

class A 
{
    string str;
public:
    A() = delete;
    A(string _str): str(_str) {}
    string getStr() 
    {
        return str;
    }
};

int main()
{
    unique_ptr<A[]> ptr = make_unique<A[]>(3);
    unique_ptr<A[]> arr[3] = make_unique<A[]>(3);
    // Do something here
    return 0;
}
like image 868
Panch Avatar asked Feb 06 '23 01:02

Panch


2 Answers

For an array of smart pointers:

unique_ptr<A> ptr[3];

for (auto& p : ptr)
    p = make_unique<A>("hello");
like image 124
M.M Avatar answered Feb 07 '23 18:02

M.M


You can't do that with make_unique. But you can use this:

unique_ptr<A[]> ptr(new A[3]{{"A"}, {"B"}, {"C"}});

Before C++11 - it was very hard (that can be done with placement new etc).

like image 25
ForEveR Avatar answered Feb 07 '23 19:02

ForEveR