【问题标题】:Create an array of smart pointers to a class with no default constructor创建一个指向没有默认构造函数的类的智能指针数组
【发布时间】:2017-07-12 07:41:39
【问题描述】:

我指的是question,我们能否为已删除默认构造函数的类创建一个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;
}

【问题讨论】:

  • 您询问的是 std::unique_ptr 数组,但您有 std::unique_ptr 到数组
  • 请澄清您的意思是代码中的“unique_ptr 到数组”还是“智能指针数组”

标签: c++ visual-c++ c++14


【解决方案1】:

对于智能指针数组:

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 只是因为数组的make_unique 只有一种方法(即接收大小的方法)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多