In practice, the intelligent pointer unique_ptr series in c ++ -- uses unique_ptr to avoid multi-layer if nesting
Today, I saw this article and thought it was not very nice.
We like process control too much and write too much if else in the program.
Maybe we are very clear about the logic, but it is a disaster for people who read your code.
Many people say that polymorphism is used to avoid excessive if else nesting, but sometimes you may think that writing a new class seems a little tricky, especially when the entire code is already huge.
It is also said that the if else statement can be converted to the switch statement, which can avoid multi-layer if nesting as appropriate.
In practice, the following scenario is too familiar:
Create an object A first, and then use this object to create another object B.
auto pa = CreateA(); status = doStuffByA(pa); auto pb = CreateBbyA(pa); status = doStuffByB(pb);
Like the above Code, the normal logic is very simple, but if you consider error handling, the Code becomes abnormal and troublesome.
The code below simply relies on if-else to solve the problem. It can be seen that code Nesting is very serious, and DestoryA (pa) needs to be called in many places, which is a duplicate logic.
bool Init(){ A* pa = nullptr; B* pb = nullptr; pa = CreateA(); if (pa) { if (doStuffByA(pa)) { pb = CreateBbyA(pa); if (pb) { if (doStuffByB(pb)) { } else { DestoryB(pb); DestoryA(pa); return false; } } else { DestoryA(pa); return false; } } else { DestoryA(pa); return false; } } else{ return false; } return true;}
In C ++ 11, we have the unique_ptr tool.
bool Init4(){ auto deleterA = [&](A* p){ if (p) DestoryA(p); }; std::unique_ptr pa(CreateA(),deleterA); if (!pa){ return false; } if (doStuffByA(pa.get())){ return false; } auto deleterB = [&](B* p){ if (p) DestoryB(p); }; std::unique_ptr
pb(CreateBbyA(pa.get()), deleterB); if (!pb){ return false; } if (doStuffByB(pb.get())){ return false; } pa.release(); pb.release(); return true;}
With the previous foundation, it is easy to understand:
All pa petabytes are smart pointers with custom delimiters;
Lambda expressions are used to define the delimiters;
Use the get () method of unique_ptr to Returns the stored pointer.