Without RAII
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <new>
int main()
{
int *arr = nullptr;
int *max = nullptr;
double *double_arr = nullptr;
float *float_max = nullptr;
float *float_arr = nullptr;
try{
arr = new int[100];
max = new int(300);
double_arr = new double[300];
float_max = new float(3.14);
float_arr = new float[300];
//.....do something......
//handle your garbages if something happen
goto cleanUp;
//.........do smething.......
}catch(std::bad_alloc const &ex){
std::cerr<<ex.what()<<std::endl;
}
cleanUp:
if(arr){
delete []arr;
arr = nullptr;
}
if(max){
delete max;
max = nullptr;
}
if(double_arr){
delete []double_arr;
double_arr = nullptr;
}
if(float_max){
delete float_max;
float_max = nullptr;
}
if(float_arr){
delete []float_arr;
float_arr = nullptr;
}
}
| |
With RAII
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <memory>
#include <new>
#include <vector>
int main()
{
try{
std::vector<int> arr(100);
std::unique_ptr<int> max(new int(300));
std::vector<double> double_arr(300);
std::unique_ptr<double> double_max(new double(300));
std::vector<float> float_arr(100);
std::unique_ptr<float> float_max(new float(100));
//...do something....
//the object will release the resources automatically
//even the exceptions thrown
}catch(std::bad_alloc const &ex){
std::cerr<<ex.what()<<std::endl;
}
}
| |
The performance and robustness of the standard library is damn good,
in most of the cases they outperform the handcrafted codes,
generate better object files, higher quality codes.
Since we have no question about robustness and performance,
I have no idea why there are still a lot of c++ programmers like
to deal with the codes without the help of RAII(They are not design
infrastructure like smart pointer and containers but some routine logic.)?
With RAII, I don't need to worry about I would forget to release the resource, I
don't need any goto, don't need to alter codes of goto part when I add or
remove some codes.In the conclusion, RAII make the codes become more
robust, easier to maintain and read,so what make tons of c++ programmers
refuse RAII?
I could understand if they refuse TMP, but RAII is a basic of c++ but not some
rocket science.RAII are easy to learn, we don't even need to design our
class to protect the resources too, standard already provide the tools for you.
ps : in real codes I wouldn't use unique_ptr to guard a primitive type like int or double, it is just an example.