问题描述:

I have a class with two constructors:

A::A(int a) and A::A(double a).

These constructors initializes different member variables. In the first case I initialize a map and in the second case I initialize a pointer.

First case:

 A::A(int a): mymap() {}

Second case:

A::A(double a) : mypointer(NULL) {}

My question is that when two objects using these two different constructors are created, what should I consider when the destructor of this class is called? I mean is it enough to write the destructor as follows such that:

- I check whether mymap is not empty then delete the entries

- I check whether mypointer is not null then delete the mypointer.

A::~A(){

if(!mymap.empty()) { delete entries and clear the map}

if(mypointer != NULL) { delete mypointer; mypointer =NULL; }

}

Then if I initialize both variables in both constructors like:

A::A(int a): mymap(), mypointer(NULL) {}

A::A(double a) : mymap(), mypointer(NULL) {}

is my destructor safe? or should I remove if conditions and perform deletions directly.

网友答案:

You need to initialize all members in both constructors.

For example, think about the pointer you initialize in one of the constructors. Since the other constructor doesn't initialize it, then its value will be undefined and so you have undefined behavior when checking the pointer in the destructor.

网友答案:

First initialize all members variables in constructor otherwise it leads to memory errors . There is no need for check in case of mymap as mymap is not a pointer and in case of mypointer it is right to first check for NULL

网友答案:

My question is that when two objects using these two different constructors are created, what should I consider when the destructor of this class is called? I mean is it enough to write the destructor as follows such that: - I check whether mymap is not empty then delete the entries - I check whether mypointer is not null then delete the mypointer.

Your approach is technically correct - that is, check and release all resources in the destructor. Conceptually, however, I'd recommend to have two classes as it looks you need at least two completeley different interfaces and implementations.

相关阅读:
Top