c++ - C++中类的静态数据成员和静态方法是静态对象吗?

标签 c++ static lifetime storage-duration

摘自《编程语言语用学》,作者:Scott

Object lifetimes generally correspond to one of three principal storage allocation mechanisms, used to manage the object’s space:

  1. Static objects are given an absolute address that is retained throughout the program’s execution.

  2. Stack objects are allocated and deallocated in last-in, first-out order, usually in conjunction with subroutine calls and returns.

  3. Heap objects may be allocated and deallocated at arbitrary times. They require a more general (and expensive) storage management algorithm.

类的静态数据成员和静态方法是在 PLP 书中的 C++ 静态对象?

类的静态数据成员和静态方法的存储是在编译时还是运行时分配的?

它们分配在哪里?

谢谢。

最佳答案

Are the static data members and static methods of a class in C++ static objects in the PLP book?

静态数据成员,是的。函数内部的静态对象也是如此。也是在文件范围内声明的对象。

Are the storage for the static data members and static methods of a class allocated at compile time or run time?

如果按分配,你指的是内存分配,它们的内存占用是在编译时保留的,空间实际上是由链接器在链接时(或动态加载器在加载时)在进程空间中分配的。在任何一种情况下,都在运行时间之前。

但是,在文件或类范围内声明的静态对象在运行时初始化,在调用 main() 函数之前。

函数中定义的静态对象是不同的。它们在代码第一次流过它们时被初始化。

Where are they allocated?

无论链接器或加载器决定在哪里。这可能会受到编写您自己的链接器脚本的影响(恐怕超出了这个答案的范围)。

关于c++ - C++中类的静态数据成员和静态方法是静态对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255439/

相关文章:

java - 重新加载 java 类中的静态字段

Java 不知道从哪里开始使用这个方法来获取元素周期表

我可以存储指向 __PRETTY_FUNCTION__ 的指针以供以后使用,还是需要立即复制该字符串?

reference - Rust 生命周期错误预期具体生命周期但发现绑定(bind)生命周期

c++ - 左值绑定(bind)到右值引用

c++ - 通过返回指向 map 的指针访问 map C++

c++ - 在 winapi 中使用 lambda 函数对 vector 进行排序

c++ - 关于 Boost Statechart 中状态变化的通知

c# - 静态和动态 C# 之间的互操作性差

rust - 为什么不能在同一结构中存储值和对该值的引用?