c++中对象的动态初始化是什么?

2021-12-11 00:00:00 object initialization dynamic 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.

相关文章