[英]Create an array of smart pointers to a class with no default constructor
我指的是这个问题 ,我们可以创建一个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;
}
对于一组智能指针:
unique_ptr<A> ptr[3];
for (auto& p : ptr)
p = make_unique<A>("hello");
你不能用make_unique
做到这make_unique
。 但你可以用这个:
unique_ptr<A[]> ptr(new A[3]{{"A"}, {"B"}, {"C"}});
在C ++ 11之前 - 它非常难(可以通过放置新的等来完成)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.