小又的后花园 2022-03-10 16:36 采纳率: 0%
浏览 17

c++ 空指针调用使用this指针的成员函数为什么不会出错

问题遇到的现象和发生背景

最近看代码发现了空指针调用成员函数的情况,查看相关文章,基本都说明只要成员函数不调用this指针就不会有问题。
但是我自己试的时候发现下面的情况不会出现问题,感觉有点蒙了

    struct TempClass
    {
        unsigned int id1;
        unsigned long id2;
        unsigned int id3;

        TempClass()
        {
            id1 = 0;
            id2 = 0;
            id3 = 0;
            DBG_LOG("construct fun!!");
        }

        void print()
        {
            DBG_LOG("this ptr:%d", this);
            DBG_LOG("id1 ptr:%d offset : %d", &id1, (char*)&id1-(char*)this);
            DBG_LOG("id2 ptr:%d offset : %d", &id2, (char*)&id2-(char*)this);
            DBG_LOG("id3 ptr:%d offset : %d", &id3, (char*)&id3-(char*)this);
        }
    };

    ((TempClass*)0)->print();

打印结果如下:

 this ptr:0                                                                                                                           
 id1 ptr:0 offset : 0                                                                                                                 
id2 ptr:8 offset : 8                                                                                                                 
 id3 ptr:16 offset : 16 

上面是打印地址,如果打印成员变量的值,编译能通过,但是会核心已转储

    struct TempClass
    {
        unsigned int id1;
        unsigned long id2;
        unsigned int id3;

        TempClass()
        {
            id1 = 0;
            id2 = 0;
            id3 = 0;
            DBG_LOG("construct fun!!");
        }

        void print()
        {
            DBG_LOG("this ptr:%d", this);
            DBG_LOG("id1:%d ptr:%d offset : %d", id1, &id1, (char*)&id1-(char*)this);
            DBG_LOG("id2:%d ptr:%d offset : %d", id2, &id2, (char*)&id2-(char*)this);
            DBG_LOG("id3:%d ptr:%d offset : %d", id3, &id3, (char*)&id3-(char*)this);
        }
    };

    ((TempClass*)0)->print();

执行结果

44625 段错误               (核心已转储)

之前看文章提到,普通成员函数编译的时候会编译成普通函数,第一个参数是类类型的指针,也就是this。所以上面的print函数会编译程下面的函数


 void print(TempClass*  thisPtr)
 {
            DBG_LOG("this ptr:%d", thisPtr);
            DBG_LOG("id1:%d ptr:%d offset : %d", thisPtr->id1, &thisPtr->id1, (char*)&thisPtr->id1-(char*)thisPtr);
            DBG_LOG("id2:%d ptr:%d offset : %d", thisPtr->id2, &thisPtr->id2, (char*)&thisPtr->id2-(char*)thisPtr);
            DBG_LOG("id3:%d ptr:%d offset : %d", thisPtr->id3, &thisPtr->id3, (char*)&thisPtr->id3-(char*)thisPtr);
 }

但是我现在想不明白,thisPtr都已经是个空指针了,为啥还不会出错?请教下各位,这种情况是为什么?感谢!!

  • 写回答

2条回答 默认 最新

  • mzhan017 2022-03-10 17:49
    关注

    原因是第一个程序,编译器做了编译时计算。而后一个是要实际访问0地址

    评论

报告相同问题?

问题事件

  • 创建了问题 3月10日

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?