[C++-sig] Using an intrusive_ptr with a noncopyable member variable
Don
don.j.olmstead at gmail.com
Fri Oct 26 00:36:37 CEST 2007
Hello all,
Just starting to try using boost python for exposing some code I've written.
Essentially I have a class Object that has a protected constructor, that is
derived by various other classes. This class does its own reference counting via
intrusive_ptr. Because it does its own reference counting and for thread safety
I have a mutex that is entered when changing the reference count.
So the header file for the Object class, with unrelated functionality stripped
out is.
namespace Shade
{
class Object
{
protected:
Object();
public:
virtual ~Object();
// Reference counting
public:
void incrementReferences();
void decrementReferences();
unsigned int getNumberOfReferences() const;
private:
/** Number of references to the Object */
unsigned int numReferences;
/**
* Mutex for the reference counting system.
*
* Assures that a pointer isn't accidently deleted or
* left dangling when accessed by multiple threads.
*/
boost::mutex mutexRefCount;
} ;
/** Smart Pointer for the Object class */
typedef boost::intrusive_ptr<Object> ObjectPtr;
#include "ShadeObject.inl"
}
void intrusive_ptr_add_ref(Shade::Object* object);
void intrusive_ptr_release(Shade::Object* object);
I expose it to Python using the following code
BOOST_PYTHON_MODULE(Shade)
{
python::class_<Object, boost::noncopyable, ObjectPtr>("Object", python::no_init)
// class .def's
;
// Uninteresting dummy test class
python::class_<DummyObject, boost::noncopyable, DummyObjectPtr,
python::bases<Object> >("DummyObject");
}
So in C++ if I do
DummyObjectPtr test1 = DummyObject();
DummyObjectPtr test2 = test1;
std::cout << test1->getNumberOfReferences() << std::endl;
The console will say
2
Now if I do the same in Python
test1 = DummyObject()
test2 = test1
print test1.getNumberOfReferences()
The console will say
1
The Object wont attempt to delete itself until both test1 and test2 are set to
something else so Python must be keeping a reference count. It would just be
nice to know what the total number of references are across Python and C++.
Any ideas?
More information about the Cplusplus-sig
mailing list