Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 谷歌测试中的RAII内存损坏_C++_Memory_Googletest_Raii - Fatal编程技术网

C++ 谷歌测试中的RAII内存损坏

C++ 谷歌测试中的RAII内存损坏,c++,memory,googletest,raii,C++,Memory,Googletest,Raii,我已经为C指针实现了一个自动删除程序。代码在测试程序中工作,但是当我在Google测试中使用代码时,奇怪的事情发生了。我不明白为什么。我有没有用未定义的行为来写作?还是谷歌测试有什么干扰 如果注释掉了宏ASSERT\u,则下面的代码将打印: i1 = 0x8050cf0 i2 = 0x8050d00 got: 0x8050cf0 got: 0x8050d00 go delete: 0x8050cf0 go delete: 0x8050d00 创建了两个指针,警卫获取这些指针,然后删除它们。完全

我已经为C指针实现了一个自动删除程序。代码在测试程序中工作,但是当我在Google测试中使用代码时,奇怪的事情发生了。我不明白为什么。我有没有用未定义的行为来写作?还是谷歌测试有什么干扰

如果注释掉了宏
ASSERT\u,则下面的代码将打印:

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();
}
#包括
#包括
使用名称空间测试;
类范围保护{
公众:
范围保护(标准::初始值设定项列表VAL)
:VAL(VAL)
{
用于(自动ptr:VAL_u2;){

标准::cerr这是未定义的行为:

您正在将
std::initializer\u list
从构造函数参数复制到类成员中

复制
std::initializer\u list
不会复制其基础元素。因此,在离开构造函数后,无法保证
vals\u
包含任何有效的内容

改为使用成员的
std::vector
,并从初始值设定项列表构造它


我不确定您使用此防护的意图,但使用
std::unique_ptr

“我不知道您为什么要编写delete ptr;there?”在构造函数中获得输出时出现复制/粘贴错误。谢谢您的评论,我已经编辑了这个问题。