The with statement is a way to do in python what is already a normal thing in C ++. It is called RAII: Initialization of a resource is initialization.
In python, when the class object is created, the __init__ method is called (but this is not a strict guarantee). The __del__ method __del__ called by the garbage collector at some point after the object is no longer used, but it is not deterministic.
In C ++, the destructor is called at a well-defined point, so there is no need for with .
I suggest you just use something like class B (no need for class A or With).
template <typename T> class B { public: B(T& t) : m_t(t_){ m_t.bind(); } ~B() { m_t.release(); } T& m_t; }
use it as follows:
{ B<X> bound_x(x); // x.bind is called B<Y> bound_y(y); // y.bind is called // use x and y here } // bound_x and bound_y is destroyed here // so x.release and y.release is called
Johan lundberg
source share