C++ unique_ptr 和数组

标签 c++ arrays pointers unique-ptr

我尝试将数组与 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 的构造函数的参数,我该如何实现?

最佳答案

This is not working, however, if I delete the constructor of A, it works.

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

std::make_unique<T[]> 需要使用默认构造函数...

所以,提供一个,一切都应该运行良好

#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);
}

关于C++ unique_ptr 和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36953688/

相关文章:

c++ - Moodle REST 网络服务 : Problems sending an array as POST parameter

c++ - 为什么 std::string 不采用空指针?

PHP:按其值的长度对数组进行排序?

c - array[1] 不起作用,而 array+1 起作用

c++ - 在 lambda 中使用类模板参数时出现编译错误

C++:链接器子系统

python - 如何将 Python POST 数据转换为 JSON?

C# 将多个对象保存到数据库后获取 id 的列表或数组

c - c中函数的垃圾值

c - 地址分配中的问题