Change deletion order to delete pointer before variable

Viewed 76

I have a class with a plain variable, _apple, a pointer to a second variable, _orange, and a destructor that cleans up _orange.

Even though _orange is defined before _apple in my class, it is cleaned up as part of the explicitly defined destructor, and is thus deleted before apple, in contrast to the usual "LIFO" deletion order.

In my code, this is an issue, since my "apple" requires "orange" still be alive, and "orange" is mandated to be a pointer because it is virtual and dynamic.

Is there any way to change the deletion order (without any additional overhead)?

MWE:

#include <iostream>

struct Food
{
    std::string _name;
    Food(const std::string& name) : _name(name) {}
    ~Food() { std::cout << _name << std::endl; }
};

struct Meal
{
    Food* _orange;
    Food _apple;
    Meal() : _orange(new Food("orange")), _apple("apple") { }
    ~Meal() { delete _orange; }
};

int main()
{
    { Meal meal; }
    return 0;
}
orange
apple
1 Answers

You change the deletion order by changing who manages the resource (= allocated memory). If you need pointer semantics, std::unique_ptr is a good candidate for this:

struct Meal
{
    std::unique_ptr<Food> _orange;
    Food _apple;
    Meal() : _orange(std::make_unique<Food>("orange")), _apple("apple") {}
};
Related