[C++-sig] Re: shared_ptr -> weak_ptr -> shared_ptr

David Abrahams dave at boost-consulting.com
Thu Apr 14 09:55:59 CEST 2005


Andreas Beyer <beyer at imb-jena.de> writes:

> Hi.
>
> I would like to transform a shared pointer originating from a python 
> object to a weak pointer. Later I would like to transform it back to a 
> shared pointer. For some strange reason I keep getting seg-faults when 
> trying to lock the weak pointer.
> Is there any danger in storing shared pointers from python objects as 
> weak pointers?

Shouldn't be, especially in your case.  This behavior really surprises
me.  Peter, do you have anything to say about this?

> According to the weak pointer's docu, lock() returns an empty shared_ptr 
> if the refered object expired. However, in my example this shouldn't be 
> the case anyway.
>
> The test case:
>
> using namespace boost;
>
> struct A { };
>
> typedef shared_ptr<A> A_ptr_shared;
> typedef weak_ptr<A> A_ptr_weak;
>
> void transform(A_ptr_shared a) {
>   std::cerr << a.get() << std::endl;
>   A_ptr_weak aw(a);
>   std::cerr << "have weak" << std::endl;
>   A_ptr_shared as = aw.lock(); // boom!
>   std::cerr << "lock is ok" << std::endl;
>   std::cerr << as.get() << std::endl;
> }
>
> BOOST_PYTHON_MODULE(ptr_test) {
>  python::class_<A> ("A");
>  python::register_ptr_to_python< A_ptr_shared >();
>
>  python::def("transform", &transform);
> }
>
>
> The python session:
>
>>>> from ptr_test import *
>>>> a=A()
>>>> transform(a)
> 0x8190a58
> have weak
> Segmentation fault (core dumped)

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Cplusplus-sig mailing list