This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
C++ auto_ptr template query
- From: "Digvijoy Chatterjee" <chatterjee dot digvijoy at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Tue, 23 May 2006 15:33:01 +0530
- Subject: C++ auto_ptr template query
Hello,
Can anyone help me find a way prevent memory leaks in the type of code below
i tried auto_ptr template but I am still loosing 40 bytes. ([10] ints
* 4 in the Class Car)
---------------------------------------------------------
class Motor
{
public:
static int i;
Motor ()
{
if (i++ == 2)
throw 46;
}
~Motor (){}
};
class Car
{
public:
Car ()
{
a = new int[10];
M1 = new Motor;
}
~Car ()
{
delete []a;
delete M1;
}
private:
int *a;
Motor * M1;
};
int Motor::i = 0;
int main ( )
{
try
{
auto_ptr < Car > auto_car (new Car[3]);
} catch (int)
{
cout << "Car caught an int thrown from motor" << endl;
}
}
-------------------
The Car[3] object is not fully constructed ,so its destructor is not
called ,but auto_car is and so when the try scope ends ,auto_car
should ensure that the object it wraps gets deleted which should call
delete [] a and remove int*a[10], thats my flawed logic i suppose
,correct me if this is wrong
Regards
Digz