Cory Kramer
Cory Kramer

Reputation: 117906

Enforce destruction order

I have two C++ classes, which for example assume are

class A
{
};

class B
{
};

I then wrap these with SWIG to create Python bindings

%include "A.h"
%include "B.h"
...etc

On the Python side, I use these as

a = A()
b = B()

I would like to somehow enforce that the destruction order therefore be ~B() then ~A(). If they are called in the other order ~B() will segfault due to essentially dangling pointers.

Is there any way I can modify the SWIG interface to enforce the destruction of B first? Like only allow its usage in a context manager? Add a reference to an A object? Take an A argument in B's constructor and add increment its reference count?

Upvotes: 2

Views: 225

Answers (1)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

Firstly, Python doesn't guarantee destruction order. If you need something like C++'s RAII, use a context manager for that.

Secondly, if your C++ code segfaults, that's your C++ code's fault. In general, you should aim for code that doesn't even compile if not used properly. Here, I'd suggest you pass a shared_ptr<A> into the B to make sure that the A isn't destroyed before the B.

Upvotes: 3

Related Questions