Are arrays in structs freed on deletion?

2019-07-16 09:03发布

问题:

If I were to use something like this in C++,

struct socket_t {
    sockaddr_in address;
    char buffer[2048];
    int FD;
}

socket_t *clients[256];
memset(clients, 0, 256);

and then create objects in it,

socket_t **free = (socket_t**) memchr(clients, 0, 256);
*free = new socket_t;

and then use delete on some of the elements,

delete clients[index];

would all members be safely freed (especially the buffer)?

I don't want to waste 2 KiB on each item I create.

I'm asking this because I noticed sizeof returns the amount of bytes used when an array is declared with type[2048] but the size of the pointer if it's declared with type*.

回答1:

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.