内存分配(C ++)编译时/运行时? [英] Allocation of memory ( C++ ) Compile-time/Run-time?

查看:197
本文介绍了内存分配(C ++)编译时/运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这个问题是否合适,但是 -



我很好奇编译器如何为一个对象设置内存(分配内存)



对于基本数据类型,它是如何发生的?



这听起来有点幼稚,但究竟是什么呢?



这完全是一个运行时进程,或者它(编译器)有任何计划,例如做这个 ,在运行期间,它在编译期间决定,时间。我完全不知道!


一个对象,无论是原始类型,指针还是大类的实例,一定的已知量的内存。那个内存必须以某种方式留给对象。在一些情况下,该备用存储器被初始化。这个初始化是什么构造函数。它们不会预留(或分配)存储对象所需的内存。该步骤在调用构造函数之前执行。


换句话说,当对任何类型的变量进行内存分配时,在时间方面,在哪一点?

使用 new

创建的分配对象

code>或 new [] 或者在运行时通过访问freestore并且在构造函数运行之前找到足够的空间放置新对象来完成。



函数中的本地对象的分配在运行时完成。然而,这通常通过将堆栈指针移动到正确的字节大小来实现,并且现在为对象保留前一个值和新值之间的空间。



全局和静态对象的分配由编译器在编译时完成,它们的构造函数在翻译单元时运行定义在加载(通常在main()开始执行之前)。



在另一个对象中直接(不通过指针)包含的对象的分配是为该对象分配的一部分。


I am not sure how appropriate is this question, but -

I am curious about how the compiler sets memory aside for an object (allocation of memory) even before it is constructed (before even the constructor is called!).

How does it happen for primitive datatypes?

This sounds a bit naive, but what exactly is it ?

Is it entirely a run time process, or does it (the compiler) have any plans like to do this, to do that, during run-time, which it decides before hand during the compile- time. I have no idea at all!

An object, be it a primitive type, a pointer, or a instance of a big class, occupies a certain known amount of memory. That memory must somehow be set aside for the object. In some circumstances, that set-aside memory is initialized. That initialization is what constructors do. They do not set aside (or allocate) the memory needed to store the object. That step is performed before the constructor is called.

In other words, when does the memory allocation for literally ANY kind of variable happen, in terms of time, at which point? At which step in compilation (or run-time)?

解决方案

Allocation objects created with new or new[] or some variant is done at runtime, by accessing the freestore and finding enough space to place the new object, prior to the constructor running.

Allocation for local objects within a function are done at runtime. However, this is usually accomplished by moving a stack pointer the correct size of bytes, and the space between the previous value and the new value is now reserved for the object. The constructors are run after the space is run.

Allocation for global and static objects are done at compile time by the compiler, and their constructors are run when the translation unit they are defined in is loaded (usually before main() begins executing).

Allocation for objects contained directly (not via pointer) within another object is done as part of the allocation for that object.

这篇关于内存分配(C ++)编译时/运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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