Boost logo

Boost :

Subject: [boost] How to make a soft copy of a temporary Python object inside C++
From: Raul Durand (raul.durand_at_[hidden])
Date: 2010-12-07 09:06:38

Hello everybody,

Maybe it is obvious but I could not figure out how to solve it yet..

Consider the A and B classes:

Class B
   int func() {return 1; }

class A
  void setB(B & b_instance)
     b = &b_instance;
     // if in Python setB is called as: a=A(); a.setB(*B()*) where B()
creates a temporary,
     // the b pointer becomes invalid after setB() function gets out of

  B * b;



    .def("setB", &A::setB);


The function A::setB sets the b data member of class A.
b is a pointer to an object of class B.

In Python I can use:


that's ok since 'b' exists as long as 'a', which could be dangerous.

Things get worse when in Python I write:


because the pointer b in class A gets invalid when the setB function gets
out of scope.

So, how can I avoid Python for destroying the temporary and keep the object
alive in C++?
Does it have anything to do with the object ownership? Is there a way to
change the ownership?

Can I make a soft copy of the b_instance object inside the setB function? so
it would increase the object counter and keep it alive and consequently the
b pointer will not get invalid.
I want to avoid making a deep copy.

Thanks in advance.

Raul Durand

Boost list run by bdawes at, gregod at, cpdaniel at, john at