Posts Tagged ‘object factories’

Out With The Old, In With The New

April 26, 2016 4 comments

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: , ,
%d bloggers like this: