Is the element really shared? That is, after creation, do you keep a pointer into the object for your own purposes or are you doing this just to avoid user memory leaks?
If the memory is not actually shared I would not use a shared_ptr
. Note that by using shared_ptr
as your return type you are forcing the use of both dynamic allocation and a particular implementation of a smart pointer, but limiting the use of the stack for your type and other smart pointer types that might be more appropriate (you cannot extract membership from a shared pointer)
If you really want to make sure that the call will not leak (that is, if the user calls your function the returned memory will be handled 'somehow', you could use std::auto_ptr
or boost::unique_ptr
(the last one being unstandard even in C++0x). Both solutions allow calling code to extract the pointer from the smart pointer and use a different approach to memory management (even if it can be cumbersome in some cases).
struct type {
std::auto_ptr<type> create();
};
std::auto_ptr<type> ap = type::create();
std::shared_ptr<type> sp( type::create().release() );
type::create(); // will not leak memory
type *rp = type::create().release(); // user specifically requested a raw pointer!