c++ - 将删除顺序更改为在变量之前删除指针
问题描述
我有一个带有普通变量的类_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
解决方案
您可以通过更改管理资源的人员(= 分配的内存)来更改删除顺序。如果您需要指针语义,std::unique_ptr
这是一个很好的选择:
struct Meal
{
std::unique_ptr<Food> _orange;
Food _apple;
Meal() : _orange(std::make_unique<Food>("orange")), _apple("apple") {}
};
推荐阅读
- css - CSS中的反椭圆
- hibernate - Hibernate 5.2.0.Final java.lang.NoSuchMethodError: org.hibernate.Session.close()V
- html - 如何制作全宽 Bootstrap 轮播滑块?
- autocomplete - WebStorm CSS 单元选择建议第一选择
- java - 如何正确序列化/反序列化 Java Object[]?
- node.js - 在基于 NodeJS 的系统中支持多个用户的最佳方式是什么?
- angular - 角度行为主题和订阅组件
- angular - UiRouter 在路由更改之前滚动到上一页位置
- java - 如何在 Spring Data JDBC 中将实体映射到表?
- python-3.x - 在熊猫中将数组对象更改为字符串