RSS

Factory Method and Automatic Pointers

17 Dec

In general when a factory method returns an instance of the created object, in C++, it is a pointer to a dynamically created memory or a resource.

Resource* factory(); // allocates dynamically

Factory method pattern does not talk about the lifetime of the object it creates. It depends upon the caller of the factory to release the resource. It can do better here. A factory method can act smarter by returing the dynamically allocated pointer by wrapping it in an automatic pointer (auto_ptr).

auto_ptr <Resource> factory(); // allocates dynamically

Returning an automatic pointer strongly indicates ownership transfer as well as
takes care of releasing the resource.

{
auto_ptr <Resource> rtemp;
rtemp = factory();
.
.
.
} // rtemp freed here automatically even in the face of exceptions!!
—–

 

 
1 Comment

Posted by on December 17, 2010 in C++ Programming

 

One response to “Factory Method and Automatic Pointers

  1. dicas para wordpress

    December 7, 2012 at 12:04 PM

    Hi there, its good piece of writing regarding media print, we all be familiar with media is a enormous source of data.

     

Leave a comment