Home > C++ > Out With The Old, In With The New

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:

  1. 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.
  2. 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++ Tags: , ,
  1. April 28, 2016 at 4:56 am

    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++.

    • April 28, 2016 at 5:13 am

      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

      • April 28, 2016 at 9:59 am

        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.

      • April 28, 2016 at 12:44 pm

        Thanks for your input.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: