-
Notifications
You must be signed in to change notification settings - Fork 0
/
class_constructor_throws.cpp
58 lines (51 loc) · 1.05 KB
/
class_constructor_throws.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <stdexcept>
#include <vector>
class AnotherClass {
public:
AnotherClass()
{
std::cout << "AnotherClass()\n";
}
~AnotherClass()
{
//this is called however
std::cout << "~AnotherClass()\n";
}
};
class MyClass {
public:
MyClass()
: a()
{
std::cout << "MyClass()\n";
some_memory = new int[50]; //this memory will be leaked
v = std::vector<int>(10); //this gets cleaned up when the vector is destroyed
throw std::runtime_error("Error");
}
~MyClass()
{
//Destructor is not run if an exception
//is thrown in the constructor
std::cout << "~MyClass()\n";
delete[] some_memory;
}
void func()
{
}
private:
int* some_memory;
std::vector<int> v;
AnotherClass a;
};
int main()
{
try {
MyClass a;
a.func();
} catch (std::runtime_error& e) {
std::cout << "got a runtime error: " << e.what() << "\n";
}
std::cout << "end\n";
return 0;
}