My class have member function that take pointer of it's own type as it's 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 an answer says that still reachable is fine, no leak. Then, when I try this:
Object* obj = new Object();
obj1->add_child(new Object());
delete obj;
obj = NULL;
valgrind's 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
It's obvious that I didn't delete the new Object() pointer that passed as an argument. So, how do I delete that pointer?
DETAILED UPDATE
definition of add_child(Object* obj):
void add_child(Object* obj) {
container.add_child(obj);
}
container is a member of Object which is an instance of template class.
Container<Object> container;
The Container definition is:
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 childrens is actually a std::multimap.
I hope this not too long for just a question.
Objectclass. You should really be using smart pointers (e. g.unique_ptrorshared_ptr) instead, though.72,704 bytes in 1 blocks, which doesn't match the size of the lost pointers in the second program. Do you have an idea what could be a such a large object in your program? (since it says "1 block", it's probably an array, given such a large size)