在这种情况下,C ++的此指针可以为NULL [英] In which case the C++ this pointer can be NULL

查看:52
本文介绍了在这种情况下,C ++的此指针可以为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用该指针的时候在类构造函数中遇到了一个问题,但是那时该指针恰好为NULL。例如

I experienced an issue that in the class constructor while I was using this pointer, but this pointer happen to be NULL at that time. for example

MyClass::MyClass()
{
   //this pointer happen to be NULL in this case, and it crash in teh m_callbackfunc because it does not handle null input.
   m_callbackFunc(this);
}

我想知道为什么这个指针可以为空吗?

I wonder why this pointer can be null? and in which case this pointer can be null?

推荐答案

this 指针可以为NULL。

The only way a this pointer can be NULL is if some code in the program has exhibited undefined behaviour.

例如,可以通过

  void *place = nullptr;
  MyClass *object = new (place) MyClass();

问题是这实际上取消了对NULL指针的引用,因此具有未定义的行为。因此, MyClass 构造函数可能会将 this 作为NULL。任何其他影响也是可能的-未定义行为的性质就是这样。

The problem is that this effectively dereferences a NULL pointer, so has undefined behaviour. So it is possible that MyClass constructor will have this as NULL. Any other effect is also possible - such is the nature of undefined behaviour.

某些调试器还报告为空指针。但这实际上并不表示 为NULL的迹象。这表明 this 是语言关键字,而不是调试器可以在目标文件中找到的带有符号名称的东西。其他一些调试器在被要求评估 this 时仅报告当前函数/作用域/范围中不存在该名称的任何东西-可能是因为C ++编译器实现了 $

Some debuggers also report this to be a NULL pointer. But that isn't actually a sign of this being NULL. It is a sign that this is a language keyword rather than something with a symbolic name in object files that the debugger can find. Some other debuggers, when asked to evaluate this simply report that nothing with that name exists in the current function/scope/whatever - possibly because the C++ compiler implements this by passing a value in a machine register.

这篇关于在这种情况下,C ++的此指针可以为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆