在下面的例子中
class X
{
int *r;
public:
X() {
cout << "X is created";
r = new int[10];
};
~X() {
cout<< "X is destroyed";
delete [] r;
};
};
class Y
{
public:
Y() {
X x;
throw 44;
};
~Y() {
cout << "Y is destroyed";
};
};
我从一个站点获得了这个 RAII 示例,并提出了一些疑问。请帮忙。
- 在 x 的构造函数中,我们没有考虑“如果内存分配失败”的场景。
- 这里 Y 的析构函数是安全的,因为 y 构造函数没有分配任何内存。如果我们还需要在 y 构造函数中进行一些内存分配怎么办?