[C++-sig] Can developer find true happiness with shared_ptr?

Neal Becker ndbecker2 at gmail.com
Sat Jun 3 02:31:03 CEST 2006


Continuing the quest,

I'm working on a framework for signal processing.  The plan is to create
objects in python and then compose them.  The components are (in general)
polymorphic.  From python the components can be configured and controlled. 
Also, components can be retrieved back to python from the composites.

I've been doing some experiments with boost::shared_ptr.  It appears that if
components are always stored as shared_ptr, and always passed (by value) as
shared_ptr, that life is easy.

For example:

struct cnt {
  cnt (int _n) : n (_n) {}
  int n;
};

struct A {
  A (boost::shared_ptr<cnt> _c) : c (_c) {}
  boost::shared_ptr<cnt> c;
  int get() const { return c->n; }
  void inc() { c->n++; }
};

using namespace boost::python;

BOOST_PYTHON_MODULE (testA) {
  class_<cnt> ("cnt", init<int>());
  class_<A> ("A", init<boost::shared_ptr<cnt> >())
    .def ("get", &A::get)
    .def ("inc", &A::inc)
    .def_readwrite ("c", &A::c)
    ;
}
>>> c = cnt (0)
>>> a = A(c)
>>> b = A(c)
>>> a.c
<testA.cnt object at 0x2aaaaab4b730>
>>> b.c
<testA.cnt object at 0x2aaaaab4b730>

It appears that this design meets all the requirements.  Not demonstrated
above, but also polymorphism works as expected.  Note that here only
polymorphism of components written in c++ is required, and that is all I
tested.  I did not test or require that components could be subclassed in
python.

Just wondering if I am on the right path here?  In particular, it seems
there is no need for non-default call or return policies to make this work,
which makes life a lot simpler.




More information about the Cplusplus-sig mailing list