I prefer this version:
~scoped_ptr() { delete this->ptr_; //this-> for emphasis, ptr_ is owned by this }
Setting the pointer to zero after deleting it is completely pointless, since the only reason you will use pointers is to allow the reference to the object in several places at the same time. Even if the pointer in one part of the program is 0, there may be others that are not set to 0.
In addition, the safe_delete macro / function template is very difficult to use correctly, because there are only two places that can be used if there is code that can be thrown between the new one and delete for this pointer.
1) Inside the catch (...) block, which redraws the exception, and is also duplicated next to the catch (...) block for the path that does not throw. (Also duplicated next to each gap, return, continuation, etc., which may allow the pointer to fall out of the area)
2) Inside the destructor for the object to which the pointer belongs (unless there is code between the new and the deleted, which can cause).
Even if there is no code that could be thrown away when you write the code, this may change in the future (all that is required is for someone who comes in and adds another new one after the first). It is better to write code in such a way that it remains true even before exceptions.
Option 1 creates so many duplicates of the code and it is so easy to make a mistake that I doubt that I even called it an option.
Option 2 makes safe_delete redundant, since the ptr_ parameter that you set to 0 will go beyond the scope on the next line.
In conclusion, do not use safe_delete, since it is unsafe (it is very difficult to use correctly and leads to redundant code, even when its use is correct). Use SBRM and smart pointers.
Mankarse
source share