What is dynamic initialization of object in c++?(什么是 C++ 中对象的动态初始化?)
问题描述
什么是c++中对象的动态初始化?
请用一个简单的例子解释一下……
Please explain with an simple example...
推荐答案
动态初始化是指在编译时不知道初始化值.它在运行时计算以初始化变量.
Dynamic initialization is that in which initialization value isn't known at compile-time. It's computed at runtime to initialize the variable.
例子,
int factorial(int n)
{
if ( n < 0 ) return -1; //indicates input error
else if ( n == 0 ) return 1;
else return n * factorial(n-1);
}
int const a = 10 ; //static initialization
//10 is known at compile time. Its 10!
int const b = factorial(8); //dynamic initialization
//factorial(8) isn't known at compile time,
//rather it's computed at runtime.
也就是说,静态初始化通常涉及常量表达式(在编译时已知),而动态初始化涉及非常量表达式.
That is, static-initialization usually involves constant-expression (which is known at compile-time), while dynamic-initialization involves non-constant expression.
static int c;//this is also static initialization (with zero)!
C++ 标准 (2003) 中的第 3.6.2/1 节说,
§3.6.2/1 from the C++ Standard (2003) says,
具有静态存储持续时间的对象(3.7.1) 应为零初始化(8.5) 在任何其他初始化之前发生.零初始化和用 常量初始化表达式统称为静态初始化;所有其他初始化是动态的初始化.
Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization.
所以有两种初始化:
- 静态初始化:它可以是零初始化,也可以是使用常量表达式初始化
- 任何其他初始化都是动态初始化.
另外请注意,同一个变量可以在静态初始化后进行动态初始化.例如,看这段代码:
Also note that the same variable can be dynamically-initialized after it has been statically-initialized. For example, see this code:
int d = factorial(8);
int main()
{
}
由于 d
是一个全局变量,它具有静态存储.这意味着,根据 §3.6.2.1
,它在静态初始化阶段被初始化为 0,该阶段发生在 在任何其他初始化发生之前.稍后,在运行时,它会使用 factorial()
函数返回的值动态初始化.
Since d
is a global variable, it has static storage. That means, according to §3.6.2.1
it's initialized to 0 at the static-initialization phase which occurs before any other initialization takes place. Then later, at runtime, it's dynamically-initialized with the value returned from the function factorial()
.
这意味着,全局对象可以被初始化两次:一次是静态初始化(即零初始化),然后是在运行时动态初始化.
That means, global objects can be initialized twice: once by static initialization (which is zero-initialization) and later, at runtime, they can be dynamically-initialized.
这篇关于什么是 C++ 中对象的动态初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是 C++ 中对象的动态初始化?
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01