[C++-sig] Suppressing assignment operator in Boost.Python

Abhi abhi at qualcomm.com
Fri Apr 21 03:21:17 CEST 2006


Consider a simplified example:

// Example
#include <iostream>
class A
{
public:
  int x;
  A() : x(5) {}

private:
  const A& operator=(const A& a)
  {
    std::cout << "A::=" << std::endl;
    x = a.x;
    return *this;
  }
  A(const A& a);

};

class B
{
public:
  A aObj;
  B()
  {
    aObj.x = 6;
  }
};

Notice that the assignment operator is private, hence the aObj inside B 
needs to be manipulated in place.

The boost.python binding for this looks like (and this is what py++ also 
generates out-of-the-box):

#include "test.cpp"


namespace bp = boost::python;



BOOST_PYTHON_MODULE(Boost_YMI){
  bp::class_< B, boost::noncopyable>( "B" )
        .def( bp::init< >()[bp::default_call_policies()] )
       .def_readwrite("aObj", &B::aObj)
    ;


    bp::class_< A, boost::noncopyable >( "A" )
        .def( bp::init< >()[bp::default_call_policies()] )
        .def_readwrite( "x", &A::x );
}


But this does not compile since Boost.Python generates an assignment 
operator for the attribute aObj (which has a private assignment operator).

Is this anyway to tell Boost.Python to not generate the assignment operator 
for aObj of B.

One workaround (which is not at all elegant!) is for me to write the 
following hand-crafted methods:

void set(B& self, A& a)
{
  self.aObj.x = a.x;
}

const A& get(B& self)
{
  return self.aObj;
}

 and then not expose the aObj as an attribute but rather through these 
methods in python:
    bp::class_< B, boost::noncopyable>( "B" )
        .def( bp::init< >()[bp::default_call_policies()] )
        .def("set", &set)
        .def("get", &get, bp::return_internal_reference<>() )



thanks
- Abhi




More information about the Cplusplus-sig mailing list