[C++-sig] return object from factory function

David Abrahams dave at boostpro.com
Wed Jul 16 23:22:35 CEST 2008


on Wed Jul 16 2008, Gennadiy Rozental <rogeeff-AT-gmail.com> wrote:

> David Abrahams <dave <at> boostpro.com> writes:
>> Unfortunately I don't understand what you're doing well enough yet to be
>> able to advise.
>
> Let me try again. Here is my create function implementation:
>
> Base*
> Factory::create( .... )
> {
>  ....
> case python_object:
>    boost::python::object obj = m_python_type();
>
>    return boost::python::extract<PythonBase*>( obj )();
> }
>
> As you can see obj is automatic variable, which gets destructed as we leave the
> function create scope. Reference counter is decreased and underlying python
> object is destroyed in turn. What I need is to prevent it, because I want to
> return pointer to it from this function. It should work the same way as if I
> would write 
> new DerivedFromBase(...)

So extract and return a shared_ptr<Base>.  That will maintain ownership
of the Python object for you.

-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com



More information about the Cplusplus-sig mailing list