Debian Codegraph @

src/include/pyptr.h

raw symbols SCIP
1 #ifndef PYPTR_H
2 #define PYPTR_H
3
4 #pragma once
5
6 #include <Python.h>
7
8 // Implements a mini smart pointer to PyObject.
9 // Manages a "strong" reference to the object... to use with a weak reference,
10 // Py_IncRef it first. Unfortunately, not all PyObject subclasses (e.g.,
11 // PyFrameObject) are declared as such, so we need to make this a template and
12 // cast.
13 template <class O = PyObject>
14 class PyPtr {
15 public:
16 PyPtr(O* o) : _obj(o) {}
17
18 PyPtr(const PyPtr& ptr) : _obj(ptr._obj) { Py_IncRef((PyObject*)_obj); }
19
20 // "explicit" to help avoid surprises
21 explicit operator O*() { return _obj; }
22
23 PyPtr& operator=(const PyPtr& ptr) {
24 if (this != &ptr) { // self-assignment is a no-op
25 Py_IncRef((PyObject*)ptr._obj);
26 Py_DecRef((PyObject*)_obj);
27 _obj = ptr._obj;
28 }
29 return *this;
30 }
31
32 ~PyPtr() { Py_DecRef((PyObject*)_obj); }
33
34 private:
35 O* _obj;
36 };
37
38 #endif