S.l.e!ep.¢%

像打了激速一样,以四倍的速度运转,开心的工作
简单、开放、平等的公司文化;尊重个性、自由与个人价值;
posts - 1098, comments - 335, trackbacks - 0, articles - 1
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

static 变量初始化顺序引发的bug

Posted on 2008-12-03 22:28 S.l.e!ep.¢% 阅读(154) 评论(0)  编辑 收藏 引用 所属分类: VCOther

static 变量初始化顺序引发的bug

没想到会遇到这样的问题,

在VC6环境下测试,重点请看红色字体与图片。

 

#include "stdafx.h"

#include <stdio.h>

 

typedef struct sData

{

    static const char* text;

    static int  val_a;

    static int  val_b;

} sData, *Self_Ptr;

 

typedef struct 

{

    char* text;

    intval_a;

    intval_b;

}* Other_Ptr;

 

 

const char* sData::text = "this is a test string\0";

int  sData::val_b = 200;

int  sData::val_a = 100;

 

int main(int argc, char* argv[])

{

    Self_Ptr p_self = (Self_Ptr)&(sData::text);

    Other_Ptr p_other = (Other_Ptr)&(sData::text);

    printf("%d\n", sizeof(sData));                          //----1, static 成员不计入sizeof

    printf("val_a: %d-%d\n", p_self->val_a, sData::val_a);  //----val_a: 100-100

    printf("val_b: %d-%d\n", p_self->val_b, sData::val_b);  //----val_b: 200-200

    printf("val_a: %d-%d\n", p_self->val_a, p_other->val_a);//----val_a: 100-200

    printf("val_b: %d-%d\n", p_self->val_b, p_other->val_b);//----val_b: 200-100

    return 0;

}


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理