Skip to content
Advertisement

Python with statement in C++

I am trying to implement something similar to the Python with statement in C++. As I plan to use it mainly with Qt-OpenGL the methods are called bind and release (in Python __enter__, __exit__).

Code I came up with:

header:

JavaScript

cpp:

JavaScript

Usage:

JavaScript

Questions:

  1. Needing class A and class B feels a bit clumsy. Is there a better alternative?
  2. Are there any draw backs in using && instead of &? It would make the usage of tempory objects possible (e.g. With w(X(), y);)

Advertisement

Answer

The with statement is a way to do in python what is already the normal thing in C++. It is called RAII: Resource acquisition is initialization.

In python, when a class object is created, the __init__ method is called (but this is not a strict guarantee). The __del__ method is called by the garbage collector at some point after the object is no longer in use, 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).

JavaScript

use it like this:

JavaScript
Advertisement