user2188453
user2188453

Reputation: 1145

The behavior of dynamically allocated class array

Assuming if class A has some dynamic allocated data array, and class A has a user-defined destructor to release the memory allocated by A (RAII style).

Then if we create a dynamic array of class A, lets call it array B, and use the standard free function to free resource claimed by B, can we ensure that each dynamic arrays within A has also been properly released?

And what about the situation when there are nested type relationship of B and A? can all the resources of 'A's get properly destoried after 'B's are freed?

Upvotes: 0

Views: 56

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477378

It all depends how you do it. Here's a perfectly sensible way of using free:

char * addr = static_cast<char *>(std::malloc(sizeof(A) * 2));

A * p = new (addr) A(100);
A * q = new (addr + sizeof(A)) A(50);

q->~A();
p->~A();

std::free(addr);   // fine

This will not leak memory, provided there are no exceptions in the constructor of A. As always, you must call free precisely on a pointer obtained from malloc/calloc/realloc.

Is this way of writing code insane? Definitely. Don't do it. Use std::vector<A> instead.

Upvotes: 2

Related Questions