【问题标题】:C++ unique_ptr and arraysC++ unique_ptr 和数组
【发布时间】:2016-04-30 10:23:16
【问题描述】:

我正在尝试使用具有 unique_ptr 的数组,但没有成功。
声明某个大小的 unique_ptr 的正确方法是什么?
(大小是一些参数)。

unique_ptr<A[]> ptr = make_unique<A[]>(size);

这是一个例子:

#include <iostream>  
#include <string>  
#include <vector>
#include <functional>
#include <memory>

using namespace std;

class A {
    string str;
public:
    A(string _str): str(_str) {}
    string getStr() {
        return str;
    }
};

int main()
{
    unique_ptr<A[]> ptr = make_unique<A[]>(3);
}

这不起作用,但是,如果我删除 A 的构造函数,它会起作用。
我希望 3 代表数组的大小,而不是 A 的构造函数的参数,我该如何实现?

【问题讨论】:

  • 提示:使用 4 个空格缩进将文本标记为代码
  • 为什么不使用std::unique_ptr&lt;std::vector&lt;A&gt;&gt; ptr = make_unique&lt;std::vector&lt;A&gt;&gt;(3);
  • 或者std::unique_ptr&lt;std::array&lt;A,3&gt;&gt; ptr = make_unique&lt;std::array&lt;A,3&gt;&gt;();
  • @πάνταῥεῖ,这太过分了! [使用手榴弹杀死蚂蚁] :-)。任何一种解决方案都需要使用默认构造函数。他只需要提供一个,代码就可以了
  • @WhiZTiM 是的,我已经看到你的答案了。

标签: c++ arrays pointers unique-ptr


【解决方案1】:

这不起作用,但是,如果我删除 A 的构造函数,它 有效。

当您删除用户定义的构造函数时,编译器会隐式生成一个默认构造函数。当您提供用户定义的构造函数时,编译器不会隐式生成默认构造函数。

std::make_unique&lt;T[]&gt; 需要使用默认构造函数...

所以,提供一个,一切都应该很好

#include <iostream>  
#include <string>  
#include <vector>
#include <functional>
#include <memory>

using namespace std;

class A {
    string str;
public:
    A() = default;
    A(string _str): str(_str) {}
    string getStr() {
        return str;
    }
};

int main()
{
    unique_ptr<A[]> ptr = make_unique<A[]>(3);
}

【讨论】:

  • 在这种情况下, 3 表示 ptr 的大小?即,ptr 现在包含 3 个指针?
  • @user5618793 这就是答案;如果你没有意识到,当你的类中没有其他构造函数时,有一个隐式定义的默认构造函数,这就是当你注释掉用户定义的构造函数时你的代码可以工作的原因。
  • @bku_drytt 我知道,我只是没有看到在我的代码中使用 'A()'
  • 表示保存C风格数组的连续内存大小,即3 * sizeof(A)。它不包含指向 A 对象的 3 个指针……这就是为什么需要一个默认构造函数的原因。如果它包含 3 个指针,它们可能是 nullptr,因此您不需要默认的无参数构造函数。
  • make_unique&lt;A[]&gt;(3) 在堆上使用每个对象创建 A[3],该对象必须是有效对象,默认构造。您正在调用 A() 因为对象必须是有效的(即构造的)。我真的认为应该使用 std::vector (即堆栈分配的对象来管理堆中不断增长的 A 数组),这样您就可以在调用 emplace 或 push_back 时指定构造函数。如果您需要编译时间限制,请使用 std::array.
猜你喜欢
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
相关资源
最近更新 更多