0

So I wrote an octree struct, as follows:

struct octree{
    static const int maxdepth=8;
    octree* child[8];
    uint32_t rgb;//candidates for the extra 8 bits: alpha, lighting, shape(to reduce size)
    uint8_t shape;
    ~octree(){delete[] child;}
};

The concern that I have is with the destructor...
Will it call the destructors of the children or do I have to do that myself?

Dylan Gattey
  • 1,713
  • 13
  • 34
  • fun fact: the site rejected this question with no hint as to why until looked up "stackoverflow post does not meet our quality standards" and concluded that i should capitalize the starts of sentences and i... – gentlecolts Feb 15 '13 at 01:31
  • Also, the title doesn't describe the problem very well. What is "octree"? I didn't know until I actually looked at the question. – Code-Apprentice Feb 15 '13 at 01:40
  • Octree is a pretty well-known term. I mean, it has a tag. Unless the title has changed since your comment. – Cheezmeister Feb 15 '13 at 04:17

4 Answers4

1

No, this is totally broken. Calling delete on an array results in undefined behaviour. You would need to delete each element individually (assuming it's appropriate to delete them).

A far better solution is to use a container class (e.g. std::vector or std::array), which automatically deals with cleanup for you. If you're not prepared to use an existing solution, then you need to read about the Rule of Three.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

Since you have not allocated dynamic memory for the child array, you should not use the delete[] operator to free it. However you can delete each individual element of that array to free each individual child octree. This will then call the destructors of each of the children.

A good rule to remember is that each new must have a matching delete (and vice versa). And each new[] must have a matching delete[] (and vice versa).

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

As it is, the destructor will only delete the array, but not the child octree objects. You must delete them explicitly (before deleting the array, of course).

Stu Gla
  • 1,129
  • 12
  • 16
0

What you have declared is an array of 8 octree* values. You cannot delete the array itself.

You should instead do this:

for( int i = 0; i < 8; i++ )
    if( child[i] ) delete child[i];

If you want to delete them all in one hit, you could define it like this:

octree * child;

//...
child = new octree [8];

//...
delete [] child;

The reason being that in an octree you either have no children or 8 children.

And yes: when you delete an octree instance, its destructor will be called.

paddy
  • 60,864
  • 6
  • 61
  • 103