Pergunta

I have the following struct

struct node
{
string name;
bool   isDir;
int    size;
string data; //lets store this as a string
timespec atime;
timespec ctime;
timespec mtime;
list <node*> children;

};

If I have a declare a node pointer like

node * directory = new node;

and then populate it with values

and then finally use

delete directory; //c++ construct

will all the memory space be freed? I'm particularly interested to know if the strings are automatically deallocated.

Foi útil?

Solução

When you delete a node, all of its automatical objects' destructors will be called, including that of the std::strings, which will indeed deallocate themselves, like other STL containters like the std::list in you struct would.

However, the children nodes, or any other heap objects, won't be destroyed unless you delete them yourself, for exemple by creating a destructor for your Node object, ie:

struct Node {
    ...
    list<Node*> mChildren;
    virtual ~Node() {
        for(auto& child : mChildren) delete child;
    }
}

Deleting an object first calls it's destructor, so calling delete on a child node will make it delete it's children nodes, and so on recursively until the leaves.

If the graph is a tree, the modern code would use unique_ptr to automatically destroy a node's children when the node is destroyed :

struct Node {
    ...
    list<unique_ptr<Node>> mChildren;
}

Indeed, unique_ptr assume unique ownership, as such, when their automatic unique_ptr container gets destroyed, they delete their contained pointer's pointed object, which might then destroy it's children recursively, if you built it that way.

You could also use shared_ptr for more complex graph structures, but obviously the problem is that you then need to take care of cyclic references, ie, nodes should only have weak_ptr to the root node in order to not invalidly increasing it's refcount and invalidly making the object's life unlimited.

Outras dicas

Are arrays in structs freed on deletion?

The array in your struct is an automatic object, whose life-time is tied with the instance of struct. So yes, when you delete an instance of the struct, the memory of the array is also automatically freed. This is true for all non-pointer members.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top