What happens to the member pointers when an exception occures in constructor, while allocating memory ? how can we over come this ?

Showing Answers 1 - 4 of 4 Answers

Offcourse it will result memory leak.... so use auto_ptr for such thing .. see following example, i have used two types to avoid memory leaks one is auto_ptr and another is initialize function

#include <iostream>

#include <memory>

class DataClass{

public:

int m_iValue;

DataClass(int i =0):m_iValue(i){}

void show(void) {

std::cout<<std::endl<<"Value :- "<<m_iValue<<std::endl;

}

};

class ResourceLeakFreeClass{

public:

std::auto_ptr<DataClass> m_Data1;

DataClass * m_Data2;

ResourceLeakFreeClass():m_Data1(new DataClass(100)),m_Data2(InitDataClass(200)){}

~ResourceLeakFreeClass(){

if(m_Data2){

delete m_Data2;

m_Data2 = 0;

}

}

DataClass * InitDataClass(int iData){

try{return new DataClass(iData);}

catch (...) {delete m_Data2;throw;}

}

};

int main(int argc, char* argv[])

{

ResourceLeakFreeClass RLFC;

RLFC.m_Data1->show();

RLFC.m_Data2->show();

return 0;

}

heyjoe

  • May 21st, 2007
 

When a constructor throws an exception then it means that constructor failed (duh!!) and the object is never created.

Just write a simple class to test it out yourself.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions