存储在静态 std::list 中的指针的 Valgrind false 内存泄漏

Valgrind false memory leak for a pointer stored in a static std::list

Valgrind 显示存储在静态 std::list 变量中的指针存在内存泄漏。下面是示例代码。

显示“auto t = new Abc;”的泄漏(绝对丢失:1 个块中的 4 个字节)

这是 Valgrind 中的 BUG 吗?

是否有 solution/workaround(除了手动清除 Pool::queue)?

 #include <list>

struct Abc
{
    int y = 9;
};

struct Pool
{
    static std::list<Abc*> queue;

    ~Pool()
    {
        for (auto p : queue)
        {
            delete p;
        }       
    }
};

std::list<Abc*> Pool::queue;

int main () 
{
  
  auto t = new Abc; //<<<<<<<<<<< Leak shown for this
  Pool::queue.push_back(t);

  return 0;
}

Valgrind 输出

g++ -ggdb Main.cpp

valgrind --leak-check=full ./a.out

==8807== Memcheck, a memory error detector
==8807== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==8807== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==8807== Command: ./a.out
==8807== 
==8807== 
==8807== HEAP SUMMARY:
==8807==     in use at exit: 4 bytes in 1 blocks
==8807==   total heap usage: 3 allocs, 2 frees, 72,732 bytes allocated
==8807== 
==8807== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==8807==    at 0x4C2A1E3: operator new(unsigned long) (vg_replace_malloc.c:334)
==8807==    by 0x4007D9: main (Main.cpp:26)
==8807== 
==8807== LEAK SUMMARY:
==8807==    definitely lost: 4 bytes in 1 blocks
==8807==    indirectly lost: 0 bytes in 0 blocks
==8807==      possibly lost: 0 bytes in 0 blocks
==8807==    still reachable: 0 bytes in 0 blocks
==8807==         suppressed: 0 bytes in 0 blocks
==8807== 
==8807== For counts of detected and suppressed errors, rerun with: -v
==8807== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

std::list 析构(编译器会为静态对象处理),其中的对象不会,因为那是 ~Pool 的工作,代码不会在任何地方调用它。 Abc 实例存活并且确实无法访问,泄漏报告是正确的。

@dratenik 的回答是正确答案,我根据他的回答发布修改后的代码,以便其他开发者可能会觉得有用

#include <list>

struct Abc
{
        int y = 9;
};


struct List
{
   std::list<Abc*> queue;

   void push_back(Abc* p)
   {
        queue.push_back(p);
   }

    ~List()
    {
           for (auto& p : queue)
          {
              delete p;
          }
     }


};

struct Pool
{
        static List queue;

};

List Pool::queue;

int main ()
{

  auto t = new Abc;
  Pool::queue.push_back(t);

  return 0;
}