[C++-sig] why does the "shared_ptr<X> const&" silently become 0xCCCCCCCC
Roman Yakovenko
roman.yakovenko at gmail.com
Wed Mar 11 07:19:47 CET 2009
2009/3/11 ZaeX <zaexage at gmail.com>:
> Hi, All:
>
> I used a "shared_ptr<A> const&" to store a ref of A in B;
> Well, the constructor of B seems ok, the share_ptr<A> seems to be well
> initialized;
> but after the constructor, I found the the pointer silently become
> 0xCCCCCCCC
>
> ///////////////////////////////////// below are the simplified class
> definitions
> class A{};
>
> class B
> {
> private:
> shared_ptr<A> const& m_ptr;
> public:
> B(shared_ptr<A> const& ptr):m_ptr(ptr) {cout<<m_ptr.get()<<endl;}
> void ShowPtr(cout<<m_ptr.get()<<endl;)
> }
> /////////////////////////////////// below are my exporting code
>
> class_<B, auto_ptr<B> >("B", init<shared_ptr<A> const&>())
> .def("ShowPtr", &B::ShowPtr)
> ;
> class_<A, shared_ptr<A>, noncopyable >("A")
> ;
> /////////////////////////////////// below are python code
> a = A()
> b = B(a) #cout output the ptr of a
> b.ShowPtr() #cout output 0xCCCCCCCC
>
> ============================================
> I'm quite confused by the behaviors here. Could you tell me what goes wrong?
You have to bind lifetime argument to the lifetime of the created
object: http://www.boost.org/doc/libs/1_38_0/libs/python/doc/tutorial/doc/html/python/functions.html#python.call_policies
Constructors also have call policies and you can use them.
Anyway, you will save to yourself a lot of time, if you will use
shared_ptr by value. I suggest you to change your code.
--
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
More information about the Cplusplus-sig
mailing list