为没有默认构造函数的类创建一系列智能指针
Create an array of smart pointers to a class with no default constructor
我是指这个问题,我们可以将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;
}
用于一系列智能指针:
unique_ptr<A> ptr[3];
for (auto& p : ptr)
p = make_unique<A>("hello");
您不能用make_unique
做到这一点。但是您可以使用此方法:
unique_ptr<A[]> ptr(new A[3]{{"A"}, {"B"}, {"C"}});
C 11-非常困难(可以使用新的位置等)。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 从容器创建一系列索引的最惯用方法是什么?
- 从主函数中删除在另一个函数中使用 new 创建的一系列对象
- 使用delete []删除在堆内存上创建的一系列数组
- 创建一系列超类的指针,以分配继承的类
- 试图创建一系列向量(我创建的模板化向量类)
- 为没有默认构造函数的类创建一系列智能指针
- 如何创建一系列C串
- 我如何创建和一系列函数的指针
- 从一系列图像创建 CvCapture
- 我正在尝试创建一个程序,用户在其中输入一系列数字,并且我想列出范围之间的质数
- 使用libjson创建一系列结构
- 如何使用fork()创建一系列过程
- 用C 的字符串创建一系列字符串
- 创建一系列频率
- 是否可以从一系列路径迭代器或子路径创建文件系统 TS basic_path
- 创建一系列显式函数模板实例化
- 我正在创建一系列精灵,它们应该随机出现,但它发生了
- c++:如果类禁用赋值操作符,是否有可能创建一系列类对象(使用vector?)