首页 > 解决方案 > 我们可以写一个 C++ 单元测试(不使用工具)来检测一段代码是否没有堆分配?

问题描述

要求在移动应用程序的构造函数、析构函数及其成员函数中不允许 C++ 类的堆分配。是否可以测试一段代码没有堆分配?例如,

class Test
{
public:
    Test() {}
    ~Test() {}
    void hasDynamicAllocation1() 
    {
        std::shared_ptr<int> p(new int);
        (void) p;
    }
    void hasDynamicAllocation2()
    {
        std::vector<int> v;
        v.resize(100);
    }
    void noDynamicAllocation()
    {
        member[0] = 1;
    }
private:
    int member[3];
};

单元测试:

// The following piece of code shall report failure
TEST_F(Foobar, testCase1)
{
    Test t;
    t.hasDynamicAllocation1();
}

// The following piece of code shall report failure
TEST_F(Foobar, testCase2)
{
    Test t;
    t.hasDynamicAllocation2();
}

// The following piece of code shall report pass
TEST_F(Foobar, testCase3)
{
    Test t;
    t.noDynamicAllocation();
}

标签: c++c++14

解决方案


推荐阅读