Lect18
.pdfПример1
class Hold { |
|
char *ptr; |
|
public: |
|
Hold(char *str) { |
|
|
cout << "Constructor." << endl; |
|
ptr = new char[strlen(str)+1] ; |
|
strcpy(ptr, str) ; |
|
cout << "Constructor: throwing exception..." |
|
<< endl; |
} |
throw "Exception!"; |
~Hold() { |
|
|
cout << "Destructor.\n" << endl; |
} |
delete [ ] ptr; |
void Show(){ |
|
} |
cout << "My contents: " << ptr << endl; |
}; |
31 |
Пример1
int main() {
try { Hold h = "Some string."; } catch(char *str) {
}
printf("Message caught: %s\n", str);
printf("Exiting main...\n"); cin.ignore();
}
return 0;
Результат |
|
Constructor. |
|
Global new[]. |
|
Constructor: throwing exception... |
|
Message caught: Exception! |
|
Exiting main... |
32 |
Пример2
class A { public:
A(string const& name): m_name(name)
}{ cout << "A::A(" << m_name << ")"<<endl;
~A()
{} cout << "A::~A(" << m_name << ")"<<endl;
private:
};
string m_name;
33
Пример2 |
|
Нехватка памяти и |
|
||||
|
выбросисключения |
|
|||||
class B { |
|
|
std::bad_alloc |
|
|||
|
|
|
|
|
|||
public: |
|
|
|
|
|
||
B(string const& name, size_t size) |
|
||||||
|
:m_a(name) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
,m_pData(new |
int[size]) |
|
|
|
||
|
,m_size(size) { |
|
|
|
|
|
|
} cout << "B::B(" << m_size << ")" << endl; |
|
||||||
~B() { |
|
|
|
|
|
||
delete [] m_pData; |
|
|
|
|
|
||
cout << "B::~B(" << m_size << ")"<< endl; |
|
||||||
} |
|
|
|
|
|
||
|
|
Результат: |
|
|
|||
private: |
|
|
|
|
|
||
A m_a; |
A::A(Test) |
|
|
||||
size_t m_size; |
A::~A(Test) |
|
|
||||
int * m_pData; |
Error: bad |
|
|
||||
}; |
|
|
allocation |
|
34 |
||
|
|
|
|
Выбросисключенияв деструкторе
Недопускайтевыбросаисключенийв деструкторахобъектов!
ВC++ выбросисключенияв деструктореприводиткаварийному завершениюработыпрограммы!
35
Спасибозавнимание!
36