创建一个智能指针数组,指向一个没有默认构造函数的类。

4

我参考了这个问题,我们能否创建一个指向没有默认构造函数的类的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;
}

2
你正在询问关于*std::unique_ptr数组,但你有一个指向数组的std::unique_ptr*。 - Zereges
请澄清您是否指的是您代码中的“数组的unique_ptr”,还是“智能指针的数组”。 - M.M
2个回答

7

对于一个智能指针数组:

unique_ptr<A> ptr[3];

for (auto& p : ptr)
    p = make_unique<A>("hello");

2
你不能使用 make_unique 实现这个。但是你可以使用如下方法:
unique_ptr<A[]> ptr(new A[3]{{"A"}, {"B"}, {"C"}});

在C++11之前,这非常困难(可以使用放置new等方法来完成)。


你能否更具体地说明为什么我们不能使用 std::make_unique 来做那件事,或者提供一些参考资料会很有帮助。 - Panch
1
@Panch,仅因为make_unique用于数组只有一个方法(即接收大小的方法)。 - ForEveR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接