测试采用二维数组但传递unique_ptr的方法

Testing a method that takes a two dimensional array - but passing a unique_ptr

本文关键字:unique ptr 方法 二维数组 测试      更新时间:2023-10-16

测试遗留代码。

如果我为以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_ptrinner_input必须是vector