谷歌测试中的RAII内存损坏

RAII memory corruption in Google Test

本文关键字:内存 损坏 RAII 测试 谷歌      更新时间:2023-10-16

我已经为c指针实现了一个自动删除器。代码在测试程序中工作,但当我在Google test中使用代码时,奇怪的事情发生了。我不明白为什么。我写的是未定义的行为吗?或者Google Test会以某种方式干扰?

下面的代码,如果宏ASSERT_THAT被注释掉,打印:

i1 = 0x8050cf0
i2 = 0x8050d00
got: 0x8050cf0
got: 0x8050d00
go delete: 0x8050cf0
go delete: 0x8050d00

创建了两个指针,守卫得到这些指针,然后删除它们。到目前为止完全符合要求。

如果宏是活动的,结果是:

i1 = 0x8054cf0
i2 = 0x8054d00
got: 0x8054cf0
got: 0x8054d00
go delete: 0x8054c01

由于某种原因,代码删除了另一个指针,然后删除了一个指针。我完全糊涂了。你能帮忙发现问题吗?

#include <iostream>
#include <gmock/gmock.h>
using namespace testing;
class Scope_Guard {
public:
  Scope_Guard(std::initializer_list<int*> vals)
    : vals_(vals)
    {
    for (auto ptr: vals_) {
      std::cerr << "got: " << ptr << std::endl;
    }
  }
  ~Scope_Guard() {
    for (auto ptr: vals_) {
      std::cerr << "go delete: " << ptr << std::endl;
      delete ptr;
    }
  }
  Scope_Guard(Scope_Guard const& rhs) = delete;
  Scope_Guard& operator=(Scope_Guard rhs) = delete;
private:
  std::initializer_list<int*> vals_;
};
TEST(Memory, GuardWorksInt) {
  int* i1 = new int(1);
  int* i2 = new int(2);
  std::cerr << "i1 = " << i1 << std::endl;
  std::cerr << "i2 = " << i2 << std::endl;
  Scope_Guard g{i1, i2};
  ASSERT_THAT(1, Eq(1)); // (*)
}
int main(int argc, char** argv) {
  InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

未定义行为:

你正在从构造函数参数复制一个std::initializer_list到一个类成员。

复制std::initializer_list并不复制其底层元素。因此,离开构造函数后,不能保证vals_包含任何有效的内容。

为成员使用std::vector,并从初始化列表中构造它。

我不确定你对这个守卫的意图,但可能更容易使用std::unique_ptr