简体   繁体   English

何时将内存分配给C ++中的静态变量

[英]When is memory allotted to static variables in C++

I am a newbie to C++ and facing a problem. 我是C ++的新手,面临一个问题。

I read in a book that memory is allotted to a static variable, once the object is created of that class. 我在一本书中读到,一旦创建了该类的对象,就会将内存分配给静态变量。 Now, what if I make this static variable global ? 现在,如果我将这个静态变量设为全局怎么办? When would be it initialized in that case ? 什么时候会在那种情况下初始化?

Plus, I have also read in some articles that static variables are allotted on heap and they dont rely on the construction of objects...is this true ? 另外,我还在一些文章中读到静态变量是在堆上分配的,它们不依赖于对象的构造......这是真的吗? If yes, please explain the memory initialization steps to me, I need help. 如果是,请向我解释内存初始化步骤,我需要帮助。

Thanks a lot ! 非常感谢 !

First: STOP THINKING ABOUT GLOBAL VARIABLES IN C AND C++, or you will perpetuate your state of confusion. 第一:停止思考C和C ++中的全局变量,否则你将使你的混乱状态永久化。 The issue is more complex than in, eg, Python or Pascal, and therefore you can't just use a single word for the concept(s). 问题比Python或Pascal更复杂,因此您不能只使用单个词来表示概念。

Second, there is no "heap" or "stack" -- these are operating system and CPU details, and have nothing to do with the abstract C++ language specification. 其次,没有“堆”或“堆栈” - 这些是操作系统和CPU细节,与抽象C ++语言规范无关。

Now, variables have 1) scope, 2) linkage and 3) storage class. 现在,变量有1)范围,2)链接和3)存储类。 The static keyword is used to affect the all three aspects, depending on where you use it. static关键字用于影响所有这三个方面,具体取决于您使用它的位置。

Scope : where the variable is declared. 范围 :声明变量的位置。 If within a function, it is a function-scope, if outside of a function, it is file-scope (what you probably refer to as "global variable"). 如果在函数内,它是函数作用域,如果在函数之外,它是文件作用域(你可能称之为“全局变量”)。

Linkage : whether the variable is accessible from other compilation units (relevant when your program consists of multiple source files). 链接 :是否可以从其他编译单元访问变量(当程序包含多个源文件时相关)。

Storage class : 存储类

Static variables are allocated in implementation-defined manner upon program startup, and they live until the program ends. 静态变量在程序启动时以实现定义的方式分配,并且它们一直存在直到程序结束。 They cannot be "freed" or "reallocated". 它们不能被“释放”或“重新分配”。 (a typical implementation are BSS and DATA segments as others have mentioned). (典型的实现是其他人提到的BSS和DATA段)。

Automatic variables exist only at function scope, they are allocated (and possibly initialized) on function entry (usually on the CPU's stack) and deallocated on function exit. 自动变量仅存在于函数范围内,它们在函数入口上分配(并可能初始化)(通常在CPU的堆栈上)并在函数出口处取消分配。

Dynamic storage class is what you probably refer to "the heap". 动态存储类是您可能引用的“堆”。 Those are variables whose storage is directly manipulated through malloc/free or new/delete. 这些变量的存储直接通过malloc / free或new / delete进行操作。 Storage for static variables is managed in a VERY different way than dynamic storage, and the two kinds of storage are fundamentally incompatible. 静态变量的存储以与动态存储非常不同的方式进行管理,这两种存储从根本上是不兼容的。

Example: 例:

===
// ALL file-scope variables have static storage class
int global1;        // file-scope, external linkage
static int global2; // file-scope, internal linkage

void f()
{
  static int x;     // static storage class, function-scope
  int y;            // automatic storage class, function-scope

  free(&x);         // ILLEGAL, WILL CRASH!
  free(&y);         // DITTO!
  free(&global1);   // DITTO!
}
===

Now, all variables with static storage class (global1, global2 and x) are allocated and initialized before program startup. 现在,所有具有静态存储类(global1,global2和x)的变量都会在程序启动之前进行分配和初始化。 If you do not specify initial values, they are default-initialized in UNSPECIFIED ORDER. 如果未指定初始值,则会在“缺省订单”中对其进行默认初始化。 (For primitive types, this just means filling with zeros). (对于原始类型,这只意味着填充零)。

Static variables are deallocated only at program exit. 静态变量仅在程序出口处解除分配。 This means, that 'x' in function f will be initialized ONLY ONCE (at program startup) and that it will RETAIN ITS VALUE between invocations of the function (as opposed to y which will be allocated on each function entry and deallocated at each function exit, thus also its value destroyed). 这意味着,函数f中的'x'将仅在初始化时(在程序启动时)并且它将在函数的调用之间保持其值(与将在每个函数入口上分配并在每个函数处取消分配的y相对)退出,因此它的价值也被破坏了)。 Note that using static variables within functions is very incompatible with multithreading and reentrancy, unles you know very well what you're doing. 请注意,在函数中使用静态变量与多线程和重入非常不兼容,unles你很清楚自己在做什么。

Static variables are not at all stored in Heap. 静态变量根本没有存储在Heap中。

Uninitialized static variables are stored in BSS segment. 未初始化的静态变量存储在BSS段中。

Initialized static variable are stored in Data Segment. 初始化的静态变量存储在数据段中。

You can read this article which explains all of it in a great way: http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory 你可以阅读这篇文章,它以一种很好的方式解释了所有这些: http//duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory

On programstart (before main) memory will be allocated for your static global variable. 在programstart(在main之前),将为您的静态全局变量分配内存。

I have no idea for the 2nd question. 我不知道第二个问题。

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

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