#include <iostream>
using namespace std;
class Resource {
public:
Resource(size_t size) : size(size), buffer(NULL) {
init(size);
}
~Resource() {
release();
}
void init(size_t size) {
if (size > 250) {
throw "too large!";
}
this->size = size;
this->buffer = new int[size];
cout << "init size " << this->size << endl;
}
void release() {
cout << "release size " << this->size << endl;
if (buffer != NULL) {
delete[] buffer;
buffer = NULL;
}
this->size = 0;
}
void DoubleSize() {
size_t size = this->size;
release();
init(size * 2);
}
size_t Size() {
return size;
}
private:
size_t size;
int *buffer;
};
class ResourceA: public Resource {
public:
ResourceA(size_t size) : Resource(size) {
cout << "ResourceA ctor\n";
}
~ResourceA() {
cout << "ResourceA dtor\n";
}
};
class ResourceB: public Resource {
public:
ResourceB(size_t size) : Resource(size) {
cout << "ResourceB ctor\n";
}
~ResourceB() {
cout << "ResourceB dtor\n";
}
};
class ResourceAB {
public:
ResourceAB(): a(10), b(100) {
cout << "ResourceAB ctor\n";
}
~ResourceAB() {
cout << "ResourceAB dtor\n";
}
void DoubleSize() {
a.DoubleSize();
b.DoubleSize();
}
void Size() {
std::cout << "a " << a.Size() << "; b " << b.Size() << std::endl;
}
private:
ResourceA a;
ResourceB b;
};
int main()
{
ResourceAB ab;
try {
ab.Size();
ab.DoubleSize();
ab.Size();
ab.DoubleSize();
ab.Size();
}catch(const char* msg) {
cerr << msg << endl;
ab.Size();
}
}
init size 10
ResourceA ctor
init size 100
ResourceB ctor
ResourceAB ctor
a 10; b 100
release size 10
init size 20
release size 100
init size 200
a 20; b 200
release size 20
init size 40
release size 200
too large!
a 40; b 0
ResourceAB dtor
ResourceB dtor
release size 0
ResourceA dtor
release size 40
评论