为没有默认构造函数的类创建一系列智能指针

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

本文关键字:创建 一系列 智能 指针 默认 构造函数      更新时间:2023-10-16

我是指这个问题,我们可以将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做到这一点。但是您可以使用此方法:

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

C 11-非常困难(可以使用新的位置等)。