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;
}
For an array of smart pointers:
unique_ptr<A> ptr[3];
for (auto& p : ptr)
p = make_unique<A>("hello");
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With