Returning std::unique_ptr from the factory method is great and should be a recommended practice. The message it sends (IMO): Now you are the sole owner of this object. In addition, for your convenience, the object knows how to destroy itself.
I think this is much better than returning a raw pointer (where the client must remember how and if to delete this pointer).
However, I do not understand your comment about releasing the pointer in order to extend its life. In general, I rarely see any reason for calling release on smartpointer, since I believe that pointers should always be controlled by some kind of RAII structure (about the only situation when I call release ) is to put the pointer in another controlling data structure e.g. a unique_ptr with another deleter, after I did something to guarantee extra cleanup).
Therefore, the client can (and should) simply store unique_ptr somewhere (for example, another unique_ptr that was moved, built from the returned one) if they need an object (or shared_ptr if they need several copies of the pointer). Thus, the clientside code should look like this:
std::unique_ptr<FooBar> myFoo = Foobar::factory(data); //or: std::shared_ptr<FooBar> myFoo = Foobar::factory(data);
Personally, I would also add a typedef for the return type of the pointer (in this case std::unique_ptr<Foobar> ) and the used deleter (in this case std :: default_deleter) for your factory object. This will simplify if you later decide to change the selection of your pointer (and therefore, you must use another method to destroy the pointer, which will be displayed as the second parameter of the std::unique_ptr ). So I would do something like this:
class Foobar { public: typedef std::default_deleter<Foobar> deleter; typedef std::unique_ptr<Foobar, deleter> unique_ptr; static unique_ptr factory(DataObject data); } Foobar::unique_ptr myFoo = Foobar::factory(data);
Grizzly Jan 03 '12 at 22:00 2012-01-03 22:00
source share