[英]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. 我指的是这个问题 ,我们可以创建一个
std::unique_ptr
数组到一个已删除默认构造函数的类,如下所示,如何传递string
参数。
#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
. 你不能用
make_unique
做到这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). 在C ++ 11之前 - 它非常难(可以通过放置新的等来完成)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.