Consider this code:
class base{
T* obj=new T[40];
//...
public:
base(){/*...*/}
virtual ~base(){
delete[] obj;
//...
}
...
};
class derived : public base{
T* obj2=new T[20];
//...
public:
derived(){/*...*/}
~derived(){
delete[] obj2;
//...
}
...
};
void func(){
base&& exmp=giveder(); //giveder() returns derived
base* dis=new derived[50];
//...
delete[] dis;
}
In the above code exmp
will be destructed properly as destructors are declared virtual. But my question is whether free store pointed to by dis
will be deallocated as expected and if it is then how?
It is apparent that sizeof(base)
and sizeof(derived)
is different. But that's not gonna mess with exmp
though will it mess with dis
? What I think is that It will not work as there's no way to figure out the sizeof(derived)
from a pointer to base and as a result it can't figure out how many bytes are needed to be freed. Although I really do want to know the language specification and whether it is legal. If that is legal, what is the workaround of freeing what is in acquisition?
A side question, arrays don't know of its own size(right?), then how are delete[] obj
and delete[] obj2
in the destructors going to release memory either?
I'm new to pointer and memory management, so I'd prefer descriptive answer. Thanks
new[]
stores bookkeeping info thatdelete[]
uses when freeing memory. Virtual destructors are called correctly whether the objects are in automatic memory or dynamic memory, and the correct number of bytes are released after the destructors are called – Cypriotchar A[10];
Thensizeof(A) == 10
. I'm just saying... – Uintathere