GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  Programming  >  C++

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



July 07, 2006 15:30:58 #1
 mohit12379   Member Since: March 2006    Total Comments: 16 

RE: What happens to the member pointers when an except...
 

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;

}

     

 

Back To Question