首页 > 解决方案 > 将删除顺序更改为在变量之前删除指针

问题描述

我有一个带有普通变量的类_apple,一个指向第二个变量的指针_orange,和一个清理_orange.

尽管之前_orange在我的类中定义过,但它作为显式定义的析构函数的一部分被清理,因此在苹果之前被删除,这与通常的“LIFO”删除顺序相反。 _apple

在我的代码中,这是一个问题,因为我的“apple”要求“orange”仍然存在,并且“orange”被强制为指针,因为它是虚拟的和动态的。

有没有办法改变删除顺序(没有任何额外的开销)?

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

标签: c++c++17

解决方案


您可以通过更改管理资源的人员(= 分配的内存)来更改删除顺序。如果您需要指针语义,std::unique_ptr这是一个很好的选择:

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

推荐阅读