Skip to content

Throwing a c++ exception in a rvalue causes an abort #1878

Closed
@madebr

Description

@madebr

Issue description

When throwing a c++ exception inside a method of an object that is an rvalue (=has no name associated) AND printing in the destructor, then the program aborts.

Reproducible example code

pybind11 c++ python module definition:

#include <pybind11/pybind11.h>
#include <exception>
#include <iostream>

namespace py = pybind11;

class callback {
public:
    callback() {}
    ~callback() {
        std::cout << "c++: callback::~callback()" << std::endl;
        py::print("Here does the crash happen");
   
    }

    void on_fatal() {
        std::cout << "c++: callback::on_fatal" << std::endl;
        throw std::runtime_error("whatever");
    }
};

PYBIND11_MODULE(pymodule, m) {
    py::class_<callback> class_callback(m, "Callback");
    class_callback
        .def(py::init<>())
        .def("on_fatal", &callback::on_fatal);
}

When using the python module as follows, the python interpreter aborts:

import pymodule
pymodule.Callback().on_fatal()

The output is:

terminate called after throwing an instance of 'pybind11::error_already_set'
  what():  SystemError: <built-in method join of str object at 0x7fbe724d4bf0> returned a result with an error set
Aborted (core dumped)

By assigning the just created object to a variable, the abort disappears:

import pymodule
cb = pymodule.Callback()
cb.on_fatal()

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions