Reputation: 1204
I have a class which has a struct with pointers as one of its member.
struct group {
void *v1,
void *v2;
};
class A {
A (group& handle)
: m_handle(handle)
private :
group m_handle;
};
There are no pointer members in class A. I don't see any issue (such as memory leaks) when no destructor is defined in A. I have learnt that when object A goes out of scope, destructor of A is called and if there are member classes present in A, then their destructors are called and so on. So, what happens to a member struct as m_handle above - do they have anything similar to destructor and how are the two void pointers in struct group deleted when object A goes out of scope?
Upvotes: 5
Views: 1317
Reputation: 436
essentially there is no default constructor/destructor neither for class nor for structure. Compiler cannot figure how to do default destructor at all. So you must implement your own constructor and destructor always if you have pointer members that you manage. If you don't own the pointers, then you don't have to care about it, but still good practice to have a constructor.
Upvotes: 0
Reputation: 90543
if group
owns those pointers it should have a destructor which release them (how depends on how you allocated them). Also, are group
's pointers allocated with new
or malloc
? Are you sure you need void*
and not some specific type?
As you have it, when and object of type group
gets destructed, nothing special happens to those two pointers, the are not released. Ideally, you should have a concept of "ownership" of these pointers. The class that allocates, is usually the one who should deallocate.
Upvotes: 0
Reputation: 3762
Yes, v1 and v2 could be leaked, if they aren't deallocated in some other part of your program. So, in the destructor of A you can delete v1 and v2 (if it's appropriate to), or you can just add a destructor to group (in c++, a struct is exactly like a class except for default visibility - stuff is public by default rather than private) and delete them there. Of course, this depends on appropriateness (maybe some other thing allocated and owns v1 and v2).
Upvotes: 4
Reputation: 4423
The structure inside the class would be cleaned up when going out of scope. HOWEVER, the memory v1, and v2 point to would NOT be automatically cleaned up.
Upvotes: 0