gpt4 book ai didi

C++ unique_ptr 和数组

转载 作者:行者123 更新时间:2023-11-30 05:28:08 24 4
gpt4 key购买 nike

我尝试将数组与 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com