[C++-sig] why does the "shared_ptr<X> const&" silently become 0xCCCCCCCC

athor thorena at gmail.com
Thu Mar 12 10:50:55 CET 2009


Hi, 
I just tried your example and could not reproduce the "feature". I made a
few minor modifications like fixing typos and adding a cout statement in the
constructor of A but nothing that should affect the result.

A few things that could cause you problems:
* Passing shared_ptr by reference and keeping refs to shared_ptrs is just as
bad as passing standard pointers. You never know when it's deallocated.
Passing by value could help (as already mentioned).

* auto_ptr is rather scary. It transfers the responsibility for deallocating
the memory whenever it is copied. I have no idea what the effects could be
in a python environment. I'd suggest using shared_ptr instead.

Here's my code if you want to look for any differences:
-----------------------------------------------------
struct A
{
	A()
	{
		cerr << "Creating A" << endl;
	}
};

class B
{
private:
	shared_ptr&lt;A> const& m_ptr;
public:
	B(shared_ptr&lt;A> const& ptr):m_ptr(ptr) 
	{
		cerr << "Creating B" << endl;
		cerr << m_ptr.get() << endl;	   
	}

	void ShowPtr() const
	{
		cout << m_ptr.get() << endl;
	}
};

BOOST_PYTHON_MODULE(pylib)
{

	class_<B, auto_ptr &lt;B> >("B",  init<shared_ptr&lt;A> const&>())
		.def("ShowPtr", &B::ShowPtr);

	class_<A, shared_ptr&lt;A>, noncopyable >("A");
}
----------------------------------------------------
from pylib import *
a = A() # Creating A
b = B(a) # Creating B, 0xABCDE
b.ShowPtr() # 0xABCDE





-- 
View this message in context: http://www.nabble.com/why-does-the-%22shared_ptr%3CX%3E-const-%22-silently-become-0xCCCCCCCC-tp22449314p22471472.html
Sent from the Python - c++-sig mailing list archive at Nabble.com.



More information about the Cplusplus-sig mailing list