C ++堆栈变量和堆变量 [英] C++ stack variables and heap variables
问题描述
当你在C ++中创建一个新的对象时,我们可以这样做:
When you create a new object in C++ that lives on the stack, (the way I've mostly seen it) you do this:
CDPlayer player;
在堆上创建一个对象时,调用 new
:
When you create an object on the heap you call new
:
CDPlayer* player = new CDPlayer();
但是当你这样做:
CDPlayer player=CDPlayer();
它创建一个基于堆栈的对象,但它和顶部示例之间的区别是什么?
it creates a stack based object, but whats the difference between that and the top example?
推荐答案
PODs的区别很重要(基本上,所有内置类型如 int
, bool
, double
等加上类似于C的结构体和仅从其他POD构建的联合体)是默认初始化和值初始化之间的差异。对于POD,一个简单的
The difference is important with PODs (basically, all built-in types like int
, bool
, double
etc. plus C-like structs and unions built only from other PODs), for which there is a difference between default initialization and value initialization. For PODs, a simple
T obj;
将保留 obj
未初始化, c $ c> T()默认初始化对象。所以
will leave obj
uninitialized, while T()
default-initializes the object. So
T obj = T();
是确保对象正确初始化的好方法。
is a good way to ensure that an object is properly initialized.
这在模板代码中特别有用,其中 T
可能是POD或非POD类型。当您知道 T
不是POD类型时, T obj;
就足够了。
This is especially helpful in template code, where T
might either a POD or a non-POD type. When you know that T
is not a POD type, T obj;
suffices.
附录: 您也可以写
Addendum: You can also write
T* ptr = new T; // note the missing ()
> T 是POD)。
(and avoid initialization of the allocated object if T
is a POD).
这篇关于C ++堆栈变量和堆变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!