Reputation: 204
As i was going through smart pointers, I ran through the following code.
Works as expected.
#include <iostream>
#include <memory>
using namespace std;
class Double
{
public:
Double(double d = 0) : dValue(d) { cout << "constructor: " << dValue << endl; }
~Double() { cout << "destructor called with exception: " << dValue << endl; }
void setDouble(double d) { dValue = d;
float temp= d/0;
cout<<"Error\n";
}
private:
double dValue;
};
int main()
{
auto_ptr<Double> ptr(new Double(3.14));
(*ptr).setDouble(6.28);
return 0;
}
As you can see there is an exception in setDouble method i.e i am trying divided by zero, since i am using the auto_ptr here even though there is the exception the allocated object for the class Double will be destroyed and destructor will be called this is as expected. But i have encountered one issue when i changed the code snippet, instead of dividing the d by zero, i use hard code value 1 and divide it by zero in this case also this is an exception, but as i am using auto pointer i was expecting the allocated object to be deleted, for my surprise the exception occurs and object of Double is not destroyed.
Not expected behavior.
#include <iostream>
#include <memory>
using namespace std;
class Double
{
public:
Double(double d = 0) : dValue(d) { cout << "constructor: " << dValue << endl; }
~Double() { cout << "destructor called with exception: " << dValue << endl; }
void setDouble(double d) { dValue = d;
float temp= 1/0;
cout<<"Error\n";
}
private:
double dValue;
};
int main()
{
auto_ptr<Double> ptr(new Double(3.14));
(*ptr).setDouble(6.28);
return 0;
}
Can anyone help me to understand this, why it is not behaving as expected when i hard code 1/0 in the setDouble method.
Thank you.
Upvotes: 0
Views: 76