Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;唯一的ptr和阵列_C++_Arrays_Pointers_Unique Ptr - Fatal编程技术网

C++ C++;唯一的ptr和阵列

C++ C++;唯一的ptr和阵列,c++,arrays,pointers,unique-ptr,C++,Arrays,Pointers,Unique Ptr,我尝试使用具有唯一\u ptr的阵列,但没有成功。 声明某个大小的唯一\u ptr的正确方法是什么? (大小是一些参数) unique_ptr ptr=make_unique(大小); 下面是一个例子: #include <iostream> #include <string> #include <vector> #include <functional> #include <memory> using namespace

我尝试使用具有唯一\u ptr的阵列,但没有成功。
声明某个大小的唯一\u ptr的正确方法是什么?
(大小是一些参数)

unique_ptr ptr=make_unique(大小);
下面是一个例子:

#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);
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
甲级{
字符串str;
公众:
A(string _str):str(_str){}
字符串getStr(){
返回str;
}
};
int main()
{
唯一性=使唯一性(3);
}
这不起作用,但是,如果我删除了的构造函数,它就会起作用。
我想让3代表数组的大小,而不是A的构造函数的参数,我如何做到这一点

这不起作用,但是,如果我删除 工作

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

需要使用默认构造函数

因此,提供一个,所有这些都应该很好地工作

#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);
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
甲级{
字符串str;
公众:
A()=默认值;
A(string _str):str(_str){}
字符串getStr(){
返回str;
}
};
int main()
{
唯一性=使唯一性(3);
}

提示:使用4个空格缩进将文本标记为代码为什么不使用
std::unique_ptr ptr=make_unique(3)?或者选择
std::unique_ptr ptr=make_unique()@πάνταῥεῖ, 太过分了![用手榴弹杀死蚂蚁]:-)。这两种解决方案都需要使用默认构造函数。他只需要提供一个和代码works@WhiZTiM是的,我看到了你的答案。在这种情况下,3代表ptr的大小?即,ptr现在包含3个指针?@user5618793这是答案;如果您没有意识到,在您的类中没有其他构造函数的情况下,会有一个隐式定义的默认构造函数,这就是为什么在注释掉用户定义的构造函数时代码会工作的原因。@bku_drytt我知道,我只是看不到“A()”的用法,它象征着保存C样式数组的连续内存的大小,这是3*sizeof(A)。它不包含指向对象的3个指针。。。这就是为什么需要一个默认构造函数。如果它有3个指针,那么它们可能是nullptr,因此您不需要默认的无参数构造函数。
make_unique(3)
在堆上用每个对象(必须是有效对象)生成一个[3],默认构造。调用()是因为对象必须是有效的(即构造的)。我真的认为应该使用std::vector(即堆栈分配的对象来管理堆中不断增长的数组),这样您就可以在调用emplace或push_时指定构造函数。如果需要编译时绑定,请使用std::array。
#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);
}