C++静态变量初始化顺序:为何代码中j的最终值为3?
为什么静态成员j的最终值不受初始化顺序影响?
你的疑惑核心在于对C++中静态初始化和动态初始化的执行顺序理解有误,具体拆解如下:
初始化阶段的关键区别
C++将全局/静态变量的初始化分为两个阶段:
- 静态初始化:针对编译期就能确定值的变量,比如
int R::j = 0;,这类初始化会在程序启动的最早阶段完成,早于任何运行时动态操作。 - 动态初始化:需要执行运行时代码才能完成的初始化,比如
R* R::notreR = new R(0);——因为它调用了R的构造函数,属于运行时操作,会在所有静态初始化完成后才执行。
你的代码执行流程
- 静态初始化阶段:
R::j先被初始化为0。 - 动态初始化阶段:执行
new R(0)调用构造函数,构造函数里的j++让j变成1。 - 进入main函数后:
- 创建
r1 = new R(1):构造函数执行j++,j变为2。 - 创建
r2 = new R(2):构造函数执行j++,j变为3。 - 后续代码没有再修改
j,所以最终输出R::j = 3。
- 创建
你之前误以为notreR的初始化会先执行,然后j的初始化把值重置为0,但实际顺序完全相反:j的静态初始化早于notreR的动态初始化,所以j的初始0值只会被后续的j++操作累加,不会被重置。
代码运行输出
r2 = R, i = 2 monR = NULL r1 = R, i = 1 monR = R, i = 2 R:: notreR = R, i = 0 monR = R, i = 1 R::j = 3
完整代码
#include <iostream> using namespace std; class R{ public: static R* notreR; static int j; int i; R* monR; R(int a){ i = a; monR=NULL; j++; } static void p(R* r){ j=0; notreR = new R(0); m(notreR); } static void q(R* r){ cout << "R:: notreR = "; m(notreR); cout << "monR = "; if(notreR->monR!=NULL) notreR->monR->m(notreR->monR); else cout << "NULL" << endl; cout << "R::j = " << j << endl; } static void m(R* r){ cout << "R, i = " << r->i << endl; } static void n(R* r){ m(r); cout << "monR = "; if(r->monR!=NULL) r->monR->m(r->monR); else cout << "NULL" << endl; } }; R* R::notreR = new R(0); int R::j = 0; class S{ public: static void main(){ R* r1 = new R(1); R::notreR->monR = r1; R* r2 = new R(2); cout << "r2 = "; R::n(r2); r1->monR = r2; cout << "r1 = "; R::n(r1); R::q(r1); } }; int main(){ S::main(); return 0; }
内容的提问来源于stack exchange,提问作者YASSINE
相关产品推荐
相关产品推荐

