何时以及为什么在堆C ++上声明成员变量 [英] When and why to declare member variables on the heap C++

查看:96
本文介绍了何时以及为什么在堆C ++上声明成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我是非常新的C ++编程,我一直在寻找一个几天的决定性的答案。 WHEN应该在堆上声明成员变量与堆栈?我发现的大多数答案已经解决了其他问题,但我想知道什么时候最好使用堆的成员变量,为什么最好堆成员而不是堆叠它们。

Ok, so I'm very new at C++ programming, and I've been looking around for a couple days for a decisive answer for this. WHEN should I declare member variables on the heap vs. the stack? Most of the answers that I've found have dealt with other issues, but I want to know when it is best to use the heap for member variables and why it is better to heap the members instead of stacking them.

推荐答案

首先要掌握两个重要的概念:

There are two important concepts to grasp first:


  1. 应该避免考虑堆和堆栈。这些是你的编译器/平台的实现细节,而不是语言。 1 而是,考虑对象生命周期:如果对象的生命周期对应于其父,还是应该比它长呢?如果需要后者,那么您需要使用 new (直接或间接)动态分配对象。

  1. One should avoid thinking in terms of "heap" and "stack". Those are implementation details of your compiler/platform, not of the language.1 Instead, think in terms of object lifetimes: should the object's lifetime correspond to that of its "parent", or should it outlive it? If you need the latter, then you'll need to use new (directly or indirectly) to dynamically allocate an object.

成员变量始终与其父成员变量具有相同的生命周期。成员变量可以是指针,并且它指向的对象可以具有独立的生存期。但是指向的对象不是成员变量。

Member variables always have the same lifetime as their parent. The member variable may be a pointer, and the object it points to may well have an independent lifetime. But the pointed-to object is not a member variable.

但是,您的问题没有一般答案。粗暴地说,不要动态分配,除非有一个很好的理由。如上所述,这些原因通常对应于终生需要与其父母不同的情况。

However, there is no general answer to your question. Crudely speaking, don't dynamically allocate unless there is a good reason to. As I hinted above, these reasons usually correspond to situations where the lifetime needs to differ from its "parent".



1。事实上,C ++标准没有真正谈论堆和堆栈。在优化或通常考虑性能时,考虑这些因素很重要,但从程序功能的角度来看,它们大多不相关。

这篇关于何时以及为什么在堆C ++上声明成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆