无法检测valgrind检测到的内存泄漏

1 c++ valgrind

下面是我的程序中新/删除操作符的模式.Valgrind说记忆"肯定会丢失".我无法得到泄漏的地方.我使用new/delete运算符是否有问题.

 class Generic
 {
        GenericInterface *gInterface; //GenericInterface is abstract class

        public:
           Generic ()
           {
                gInterface = NULL;
           }
           ~Generic ()
           {
               delete gInterface;
           }
           void Create()
           {
           gInterface = new Specific();
           }
    };

    class Specific : public GenericInterface
    {
       MyClass* _myClass; 

    public:
      Specific()
      {
         _myClass = new MyClass;
      }

      ~Specific()
      {
         delete _myClass; 
      }

    };

    int main()
    {
       Generic g;
       g.Create();
    }
Run Code Online (Sandbox Code Playgroud)

瓦尔格林德说,记忆力已经消失.

==2639== 8 bytes in 1 blocks are definitely lost in loss record 2 of 45
==2639==    at 0x4026351: operator new(unsigned int) (vg_replace_malloc.c:255)
==2639==    by 0x804D77C: Specific::Specific() (Specific.cc:13)
==2639==    by 0x804DAFC: Generic::Create() (Generic.cc:58)
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 11

你没有遵守三条规则.如果您的类管理需要清理的资源,则必须声明析构函数,复制构造函数和复制赋值运算符.您的类都没有复制构造函数或复制赋值运算符.

真的,你几乎可以肯定只是使用像unique_ptrC++ 0x 这样的智能指针; shared_ptr来自Boost,C++ TR1和C++ 0x; 或者scoped_ptr来自Boost.

导致此特定问题的可能问题是您忘记创建基类GenericInterface析构函数virtual,因此正在调用错误的析构函数MyClass,Specific并且永远不会销毁您动态创建的对象.

delete如果未声明基类析构函数,则通过指向其某个基类的指针导致对象导致未定义的行为virtual(这意味着将发生从内存泄漏到崩溃的不良事件).