简体   繁体   English

在c ++中初始化对象

[英]initialization of objects in c++

I want to know, in c++, when does the initialization of objects take place? 我想知道,在c ++中,对象的初始化何时发生?
Is it at the compile time or link time? 是在编译时还是链接时?
For ex: 例如:

//file1.cpp
extern int i;
int j=5;

//file2.cpp ( link with file1.cpp)
extern j;
int i=10;  

Now, what does compiler do : according to me, it allocates storage for variables. 现在,编译器做了什么:根据我的说法,它为变量分配存储空间。
Now I want to know : 现在我想知道:
does it also put initialization value in that storage or is it done at link time? 它是否也将初始化值放在该存储中,还是在链接时完成?

Actually there are different cases: 实际上有不同的情况:

  • global variables or static variables (not classes): these values are stored in an init section of the exe/dll. 全局变量或静态变量(不是类):这些值存储在exe / dll的init部分中。 These values are created by the linker based on the compiled object files information. 这些值由链接器根据编译的目标文件信息创建。 (initialization on loading + mapping the dll/exe into memory) (初始化加载+将dll / exe映射到内存中)
  • local non static variables: these values are set by the compiler by putting these values on the stack (push/pop on x86) (compiler initialization) 本地非静态变量:这些值由编译器通过将这些值放在堆栈上来设置(x86上的push / pop)(编译器初始化)
  • objects: memory is reserved on the stack, the actual setting of values is deferred to the call to the constructor (run-time initialization) 对象:内存在堆栈上保留,值的实际设置被推迟到对构造函数的调用(运行时初始化)
  • pointers to objects (not actually a new case): space is reserved for the pointer only. 指向对象的指针(实际上不是新的情况):仅为指针保留空间。 The object pointed to exists only after a call to new that reserves memory and calls the constructor to initialize it (run-time initialization) 指向的对象仅在调用new之后才存在,它保留内存并调用构造函数来初始化它(运行时初始化)

As you said the compiler allocates storage for variables. 正如您所说,编译器为变量分配存储空间。 I think the intialization value will also be done at compile time and not during link time. 我认为初始化值也将在编译时完成,而不是在链接时。

There are no objects in your example, just int s. 您的示例中没有对象,只有int If by "initialization" you mean when are their values assigned, those int s will be converted to word-sized entries in a data section in the object file, which will be hard-coded with their initial values. 如果通过“初始化”意味着何时分配了它们的值,那么这些int将被转换为目标文件中数据部分中的字大小的条目,这些条目将使用其初始值进行硬编码。 The data section, along with the rest of the object file, is created by the compiler, so I suppose the answer to your question is compile-time 数据部分以及目标文件的其余部分由编译器创建,因此我认为您的问题的答案是编译时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM