什么是 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.
相关文章