The short answer is that you do need to use delete
or delete []
(as appropriate) on each member pointer. As remyabel commented, delete does not change the value of the pointer, it simply deallocates the memory that that pointer was referring to.
// delete dynamically constructed members
delete newObject->test;
delete[] newObject->name;
The implementation of new
may allocate memory in ways that are different for arrays of items than for single items, so it is important when deleting that you use delete []
for the former and delete
for the later.
A more idiomatic way of handling clean-up is to perform these deletes in the destructor of the struct Student
. The members are allocated and constructed, or initialized with null pointers at construction for safety (delete
on a null pointer does nothing.)
struct Student
{
char * name;
int * test;
float gpa;
Student(): name(0), test(0), gpa(0.0f) {}
~Student() {
delete[] name;
delete test;
}
};
delete newObject
will then in turn delete the allocated members correctly, provided they were indeed allocated with new[]
and new
.
Because the destructor cannot guarantee that the members were indeed allocated this way, it is in turn best to pass the responsibility for allocating the members to member functions or constructors of the structure as well.