My class has a member function that takes a pointer of its own type as an argument.
When I do this:
Object* obj1 = new Object(); Object* obj2 = new Object(); obj1->add_child(obj2) delete obj1; delete obj2; obj1 = NULL; obj2 = NULL;
and run valgrind , the report says:
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
I read the answer , says that still reachable in order, without leakage. Then when I try this:
Object* obj = new Object(); obj1->add_child(new Object()); delete obj; obj = NULL;
valgrind report says:
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
Obviously, I did not delete the new Object() pointer, which was passed as an argument. So how to remove this pointer?
DETAILED UPDATE
add_child(Object* obj) definition add_child(Object* obj) :
void add_child(Object* obj) { container.add_child(obj); }
container is a member of Object , which is an instance of the template class.
Container<Object> container;
container definition:
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; }
Then the children are actually std::multimap .
Hope this is not too long for the question.