c++ - 我们可以写一个 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();
}
解决方案
推荐阅读
- typescript - TypeScript :: 继承问题
- c++ - 与文本编辑器无关的缺少分隔符问题
- c++ - 如何在 Eigen::Map 类的模板中使用变量作为参数
- r - R markdown::render 不打印函数返回的多个 kableExtra 对象
- ffmpeg - Ffmpeg 无法以 24fps 转换并刻录字幕
- google-sheets - 在 Google Sheets Query 函数的 SELECT 语句中使用 IF 条件
- c# - 当我在 mac 上使用 c# system.data.mysqlclient visual-studio 连接到 MySQL 数据库时,如何避免启动延迟
- r - 使用 Taxize 包从物种列表中获取姓氏数据框
- google-cloud-storage - 从 GCS 提供具有访问限制的静态页面
- react-native - 添加新表单条目时以本机反应更新先前屏幕的策略