我班有把它自己类型的指针作为它的参数成员函数。
当我这样做:
Object* obj1 = new Object();
Object* obj2 = new Object();
obj1->add_child(obj2)
delete obj1;
delete obj2;
obj1 = NULL;
obj2 = NULL;
并运行valgrind
,报告说:
HEAP SUMMARY:
in use at exit: 72,704 bytes in 1 blocks
total heap usage: 6 allocs, 5 frees, 73,098 bytes allocated
LEAK SUMMARY:
definitely lost: 0 bytes in 0 blocks
indirectly lost: 0 bytes in 0 blocks
possibly lost: 0 bytes in 0 blocks
still reachable: 72,704 bytes in 1 blocks
suppressed: 0 bytes in 0 blocks
我看了一个答案说, still reachable
优良,无泄漏。 然后,当我试试这个:
Object* obj = new Object();
obj1->add_child(new Object());
delete obj;
obj = NULL;
valgrind
的报告称:
HEAP SUMMARY:
in use at exit: 72,877 bytes in 3 blocks
total heap usage: 6 allocs, 3 frees, 73,098 bytes allocated
LEAK SUMMARY:
definitely lost: 144 bytes in 1 blocks
indirectly lost: 29 bytes in 1 blocks
possibly lost: 0 bytes in 0 blocks
still reachable: 72,704 bytes in 1 blocks
suppressed: 0 bytes in 0 blocks
很明显,我没有删除new Object()
是作为参数传递指针。 所以,我怎么删除指针?
详细UPDATE
的定义add_child(Object* obj)
void add_child(Object* obj) {
container.add_child(obj);
}
container
是其成员的Object
,其是模板类的一个实例。
Container<Object> container;
该Container
的定义是:
template<class T>
class Container {
public:
void add_child(const std::string& key, T* child) {
childrens.insert(std::pair<std::string,T*>(key, child));
}
private:
std::multimap<std::string,T*> childrens;
}
然后,儿童实际上是一个std::multimap
。
我希望这不会太长只是一个问题。