测试采用二维数组但传递unique_ptr的方法
Testing a method that takes a two dimensional array - but passing a unique_ptr
测试遗留代码。
如果我为以int[]
作为参数的方法编写测试,我会使用 unique_ptr
,这样我就不必关心清理分配的内存:
#include <memory>
bool methodToTest(int *parameter)
{
bool result = true;
// doing stuff
return result;
}
int main(int argc, char* argv[])
{
std::unique_ptr<int[]> input(new int[99]);
methodToTest(input.get());
// ASSERT(blah, blah)
return system("pause");
}
我可以为需要int[][]
的函数做类似的事情吗?喜欢
#include <memory>
#include <vector>
bool methodToTest(int **parameter)
{
bool result = true;
// doing stuff
return result;
}
int main(int argc, char* argv[])
{
//std::unique_ptr<int[][]> input; // Compiler complains: error C2087: 'abstract declarator' : missing subscript
//std::unique_ptr<std::unique_ptr<int[]>[]> input; // Nice structure, but how to get an int[][] from that?
std::vector<int*> input; // Works but I have to manually free allocated memory
methodToTest(input.data());
// ASSERT(blah, blah)
return system("pause");
}
那么,我是否必须自己关心释放分配的内存,或者是否有某种std::
方法可以为我做到这一点?
我自己找到了一些东西并建议:
#include <memory>
bool methodToTest(int **parameter)
{
bool result = true;
// doing stuff
return result;
}
int main(int argc, char* argv[])
{
std::unique_ptr<int*[]> input(new int*[44]);
std::unique_ptr<int[]> inner_input(new int[89]);
input[3] = inner_input.get();
methodToTest(input.get());
// ASSERT(blah)
return system("pause");
}
请注意,如果您想要多个unique_ptr
,inner_input
必须是vector
。
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误