C++ Array of pointers: delete or delete []?

后端 未结 8 768
春和景丽
春和景丽 2020-12-04 21:08

Cosider the following code:

class Foo
{
    Monster* monsters[6];

    Foo()
    {
        for (int i = 0; i < 6; i++)
        {
            monsters[i] =         


        
8条回答
  •  醉话见心
    2020-12-04 22:01

    delete[] monsters;

    Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

    Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

    Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

提交回复
热议问题