Factory Method and Automatic Pointers

9:48:00 PM 0 Comments A+ a-

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!!
-----
SRC: Scott Meyers