在测试中使用unique_ptr时指针错误无效
Invalid pointer error when using unique_ptr in tests
我有一个方法,它将std::unique_ptr<uint8_t[]>
作为输入并对其进行处理。在我的单元测试中,
以下是我创建和初始化此参数的方法:(在堆栈上(
uint8_t testBytes[] = {1, 2, 3, 4};
std::unique_ptr<uint8_t[]> testBytesPtr = std::make_unique<uint8_t[]>(4);
testBytesPtr.reset(testBytes);
它被传递给方法,如下所示:
myClass.processData(std::move(testBytesPtr));
在单元测试结束时,我收到以下错误消息:
free((: 无效指针: 0xbed6b8c0
以下是我的单元测试的样子:
#include "gtest.h"
#include "gmock.h" // for some deps
//...
TEST(MyClassUnittests, test1) {
// Initializing the byte array.
uint8_t testBytes[] = {1, 2, 3, 4};
std::unique_ptr<uint8_t[]> testBytesPtr = std::make_unique<uint8_t[]>(4);
testBytesPtr.reset(testBytes);
EXPECT_TRUE(myClass.processData(std::move(testBytestPtr));
}
我还应该注意,如果在堆上初始化testBytes
(例如,uint8_t* testBytes = new uint8_t()
(,错误消息变为
双重释放或损坏(快速顶部(:0xb75c1e18
任何帮助将不胜感激。
delete []
不是new []
-ed的东西,也不是你拥有的东西,是严重禁忌的。
请看这些行:
uint8_t testBytes[] = {1, 2, 3, 4};
std::unique_ptr<uint8_t[]> testBytesPtr = std::make_unique<uint8_t[]>(4);
testBytesPtr.reset(testBytes);
删除不相关的临时动态分配离开:
uint8_t testBytes[] = {1, 2, 3, 4};
std::unique_ptr<uint8_t[]> testBytesPtr(testBytes);
这会导致 dtor 启动时出现未定义的行为。
诚然,你移动std::unique_ptr
一次,但这只会改变爆炸发生的确切点。
考虑到您要测试的函数,请尝试以下操作以获取正确分配的测试数据副本:
uint8_t testBytes[] = {1, 2, 3, 4};
auto testBytesPtr = std::make_unique<uint8_t[]>(std::size(testBytes));
std::copy(std::begin(testBytes), std::end(testBytes), &testBytesPtr[0]);
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- C++中的指针否定 (!ptr == NULL)
- 使用 void 指针:void **ptr.. 如何修改共享内存的值?
- C++ 如何从指向结构的指针将 PTR 返回到 int
- 正确使用std智能指针以确保ptr安全
- 一个唯一的ptr类如何将它的实例指针传递给它的成员对象
- openv Ptr类.指针对象在调用函数后被删除