 |
返回文章
清单 8. 导致段错误和非预期结果的示例代码
1 #include <iostream>
2
3 template <class T>
4 class NumBox {
5 public:
6 NumBox (const T &input_num, NumBox<T> *input_next) : Num(input_num), Next(input_next) {
7 std::cout "" "Number Box " <<"\"" << Num <<"\"" <<" created" <<std::endl;
8 }
9 ~NumBox () {
10 std::cout << "Number Box " <<"\"" << GetValue() <<"\"" <<" deleted" << std::endl;
11 Next = 0;
12 }
13
14 NumBox<T>*GetNext() const { return Next; }
15 void SetNext (NumBox<T> *input_next) { Next = input_next; };
16 const T& GetValue () const { return Num; }
17 void GetValue (const T &input_num) { Num = input_num; }
18
19 private:
20 NumBox ();
21 T Num;
22 NumBox<T> *Next;
23 };
24
25 template <class T>
26 class NumChain {
27
28 public:
29 NumChain () : pointer(0) {};
30 ~NumChain () { delete_boxes (); };
31
32 int add (const T &new_item) {
33 return ((pointer = new NumBox<T>(new_item, pointer)) != 0) ? 0 : -1;
34 }
35
36 int RemoveBox (const T &item_to_remove) {
37 NumBox<T> *current = pointer;
38 NumBox<T> *temp = 0;
39
40 while (current != 0) {
41 if (current->GetValue() == item_to_remove) {
42 if (temp == 0) {
43 // current is pointing to the first number box of the list
44 if (current->GetNext() == 0) {
45 // Only one number box in the list
46 pointer = 0;
47 delete current;
48 current = 0;
49 } else {
50 delete current;
51 current = 0;
52 }
53 return 0;
54 } else {
55 temp->SetNext (current->GetNext());
56 delete temp;
57 temp = 0;
58 return 0;
59 }
60 }
61 current = 0;
62 temp = current;
63 current = current->GetNext();
64 }
65
66 return -1;
67 }
68
69
70 private:
71 void delete_boxes (void) {
72 NumBox<T> *current = pointer;
73 while (current != 0) {
74 NumBox<T> *temp = current;
75 delete current;
76 current = temp->GetNext();
77 }
78 }
79
80 NumBox<T> *pointer;
81 };
82
83
84 int main (int argc, char **argv) {
85 int i;
86 NumChain<int> *list = new NumChain<int> ();
87
88 for (i=0;i<10;i++)
89 list->add (i);
90
91 std::cout << "list created" << std::endl;
92
93 for (i=9; i>=0; i--)
94 list ->RemoveBox(i);
95
96 delete list;
97 }
|
返回文章
|  |
|