以下代碼來自「異常處理」中。作者試圖告訴我們,通過將所有東西都作爲對象,我們可以防止資源泄漏。 我的問題: 爲什麼'cat'和'dog'的構造函數早於'useresources'的構造函數調用?哪個構造函數被調用第一個
//: C07:Wrapped.cpp
// Safe, atomic pointers
#include <fstream>
#include <cstdlib>
using namespace std;
ofstream out("wrapped.out");
// Simplified. Yours may have other arguments.
template<class T, int sz = 1> class PWrap {
T* ptr;
public:
class RangeError {}; // Exception class
PWrap() {
ptr = new T[sz];
out << "PWrap constructor" << endl;
}
~PWrap() {
delete []ptr;
out << "PWrap destructor" << endl;
}
T& operator[](int i) throw(RangeError) {
if(i >= 0 && i < sz) return ptr[i];
throw RangeError();
}
};
class Cat {
public:
Cat() { out << "Cat()" << endl; }
~Cat() { out << "~Cat()" << endl; }
void g() {}
};
class Dog {
public:
void* operator new[](size_t sz) {
out << "allocating an Dog" << endl;
throw int(47);
}
void operator delete[](void* p) {
out << "deallocating an Dog" << endl;
::delete p;
}
};
class UseResources {
PWrap<Cat, 3> Bonk;
PWrap<Dog> Og;
public:
UseResources() : Bonk(), Og() {
out << "UseResources()" << endl;
}
~UseResources() {
out << "~UseResources()" << endl;
}
void f() { Bonk[1].g(); }
};
int main() {
try {
UseResources ur;
} catch(int) {
out << "inside handler" << endl;
} catch(...) {
out << "inside catch(...)" << endl;
}
} ///:~
他們不是。但是它們在'out <<「UseResources()」<< endl;'之前被調用。當你輸入構造函數的主體時,所有的成員對象都會調用它的構造函數。 – john