What happens if an object manages to reset/delete a unique_ptr of itself?

Viewed 91

I am having quite some trouble writing this question, so I'm just going to show a minimal example.

Suppose this is a class FruitHandler that handles an object of type Fruit using a unique_ptr, something like this:

class FruitHandler {
private:
    std::unique_ptr<Fruit> m_fruit;

public:
    FruitHandler() : m_fruit{std::make_unique<Fruit>(*this)} {}

    void some_func() {
        m_fruit.func();
    }

    void clear_fruit() {
        m_fruit.reset();
    }
}

And this is a class Fruit:

class Fruit {
private:
    FruitHandler &m_handler;

public:
    Fruit(FruitHandler &handler) : m_handler{handler} {}
    
    void func() {
        m_handler.clear_fruit();
        // Let's say I'm accessing more member variables after this
    }
}

I had something like this in my code with a few more levels of indirection between the handler and the handled object. There were a few more objects relying on the object and one of those things (or the handler) was causing a crash which I managed to solve (not by avoiding the thing I wrote) and now I'm just wondering out of interest what would happen if you would delete an object in this way. Is this somewhat similar to writing delete this? Is it undefined behavior?

0 Answers
Related