我在互联网上的代码并不完美,但在我看来,没有内存泄漏。但是要确定我使用的valgrind有不同的意见。
这是代码:
class BaseClass {
public:
virtual ~BaseClass() {}
};
class DerivedClass1 : public BaseClass {
};
class DerivedClass2 : public BaseClass {
};
class UserClass {
private:
BaseClass* base_;
public:
void setDerived(BaseClass* p_base) {
delete base_;
base_ = p_base;
}
UserClass (BaseClass *p_base){
base_ = p_base;
}
~UserClass() {
delete base_;
}
};
int main() {
UserClass * my_class = new UserClass(new DerivedClass1);
my_class->setDerived(new DerivedClass2);
return 0;
}
这是valgrind所说的:
==10125== HEAP SUMMARY:
==10125== in use at exit: 16 bytes in 2 blocks
==10125== total heap usage: 3 allocs, 1 frees, 24 bytes allocated
==10125==
==10125== Searching for pointers to 2 not-freed blocks
==10125== Checked 179,544 bytes
==10125==
==10125== 8 bytes in 1 blocks are indirectly lost in loss record 1 of 2
==10125== at 0x4C28C90: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10125== by 0x40074E: main (AbstractFactory.cpp:32)
==10125==
==10125== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==10125== at 0x4C28C90: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10125== by 0x400732: main (AbstractFactory.cpp:31)
==10125==
==10125== LEAK SUMMARY:
==10125== definitely lost: 8 bytes in 1 blocks
==10125== indirectly lost: 8 bytes in 1 blocks
==10125== possibly lost: 0 bytes in 0 blocks
==10125== still reachable: 0 bytes in 0 blocks
==10125== suppressed: 0 bytes in 0 blocks
==10125==
==10125== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 3 from 3)
--10125--
--10125-- used_suppression: 3 dl-hack3-cond-1 /usr/lib/valgrind/default.supp:1196
==10125==
==10125== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 3 from 3)
对我来说,一切似乎都是正确的。在第31行中分配了内存,在setDerived方法中,它被释放。
感谢您的帮助。
答案 0 :(得分:3)
你的代码漏了,是的。它也不是一个谜。
非常简单,你永远不会为my_class
调用析构函数。
在delete my_class;
return 0;
之前的行上添加main
。