There is example that shows that using RAII this way:
class File_ptr{
//...
File* p;
int* i;
public:
File_ptr(const char* n, const char* s){
i=new int[100];
p=fopen(n,a); // imagine fopen might throws
}
~File_ptr(){fclose(p);}
}
void use_file(const char* fn){
File_ptr(fn,"r");
}
is safe. but my question is: what if there is exception thrown in p=fopen(n,a);
then memory allocated to i
is not returned. Is this right to assume that RAII
tells you then each time you want X
to be safe then all resources acquired by X
must be allocated on stack? And if X.a
is being created then resources of a
must also be placed on stack? and again, and again, I mean finally if there is some resource placed on heap how it could be handled with RAII? If it is not mine class i.e.
fopen
is aC
function so it won't throw any exception becauseC
doesn't have exception – Aqualungint* i
to something likestd::vector<int> i
. That is, to use RAII. – Sleuth