Out With The Old, In With The New
In “old” C++, object factories had little choice but to return unsafe naked pointers to users. In “new” C++, factories can return safe smart pointers. The code snippet below contrasts the old with new.
The next code snippet highlights the difference in safety between the old and the new.
When a caller uses the old factory technique, safety may be compromised in two ways:
- If an exception is thrown in the caller’s code after the object is created but before the delete statement is executed, we have a leak.
- If the user “forgets” to write the delete statement, we have a leak.
Returning a smart pointer from a factory relegates these risks to the dust bin of history.
Categories: C++
c++, object factories, smart pointers
This is not true that old C++ factories must return raw pointers. My factories in old C++ return auto_ptr, auto_ptr in this example. As safe as new C++.
auto_ptr has been rightly deprecrated. It was a half-assed, error-prone attempt at unique_ptr. Not being able to use them in an STL container limited their use substantially. Although what you said is literally true, auto_ptr was not worth mentioning in the post.
See Scott Meyers’ take on auto_ptr: http://www.aristeia.com/BookErrata/auto_ptr-update.html
Also, see this ACCU article: http://accu.org/index.php/journals/1456
It is deprecated now, but it wasn’t deprecated when “old C++” was “current C++”. Yes, it doesn’t work in STL containers, maybe it is half-assed or whatever, but it works in the context you described very well. It is enough to understand how this simple class works to avoid problems with it. In my opinion you are trying to prove something not true.
Thanks for your input.