正确unique_ptr 1 个元素分配数组的声明
Proper unique_ptr declaration of 1 element allocated array
我需要将 API 用作项目的一部分,该项目包含一个名为ParamSet
的类,其方法定义如下:
void AddString(const std::string &, std::unique_ptr<std::string[]> v, int nValues);
该方法的目的是向对象添加一个字符串数组来描述某个参数。例如,ParamSet
对象可能需要指向nValues
字符串数组的"文件名"参数。
但是,当我尝试将方法unique_ptr
传递给仅包含 1 个字符串的数组时,代码 seg 在调用ParamSet
对象的析构函数时出错,除非我以特定方式定义unique_ptr
。
以下代码在调用Clear()
或return
时导致段错误。
ParamSet badparam;
badparam.AddString("filename", unique_ptr<string[]> (new string("test")), 1);
badparam.Clear(); // <------ CAUSES SEG FAULT
但是,以下情况不会导致 seg 故障。
ParamSet testparam;
std::unique_ptr<std::string[]> strings(new std::string[0]); // DOH, should be string[1]
strings[0] = std::string("test");
testparam.AddString("filename", std::move(strings), 1);
testparam.Clear(); // <------ NO SEG FAULT
我不明白为什么在调用AddString
的线路中创建unique_ptr
会导致 seg 错误,但在调用之外创建它则不然。
问题是您使用非数组new
来分配由unique_ptr<T[]>
管理的内存,然后这些内存将继续使用数组delete[]
,从而导致未定义的行为。
语法可以是:
badparam.AddString("filename", std::unique_ptr<std::string[]>(new std::string[1]{"test"}), 1);
std::unique_ptr
的数组专用化要求数组分配new[]
,因为它默认使用delete[]
来释放数组。
在第一个示例中,您分配的是带有new
的单个std::string
对象,而不是带有new[]
的 1 元素数组。
在第二个示例中,您正在分配一个 0 元素std::string
数组,但您需要一个 1 元素数组。
试试这个:
std::unique_ptr<std::string[]> strings(new std::string[1]); // <-- NOT 0!
// Or, if you are using C++14:
// auto strings = std::make_unique<string[]>(1);
strings[0] = "test";
testparam.AddString("filename", std::move(strings), 1);
或者:
testparam.AddString("filename", std::unique_ptr<std::string[]>(new std::string[1]{"test"}), 1);
相关文章:
- 将数组的地址分配给变量并删除
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 获取字符串的长度并将其分配给数组
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 使用递归模板动态分配的多维数组
- 如何正确填充在堆上分配的二维数组?
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 关于字符数组,我正在尝试将数组中的每个字符分配给另一个值
- 我似乎无法为指针分配一个数组,然后更改数组的内容
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 无法分配C++数组
- 如何增加以前由新运算符分配的 C++ std::list 数组的大小?
- 分配 2D 可变大小的数组
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- 动态分配字符数组的内存
- C++具有动态分配的字符数组的结构
- C 通过参考分配 /数组传递内存
- 使用字符串或字符动态分配(数组)