首先,我知道在空指针上调用方法是未定义的行为。我还知道,因为这不应该发生,编译器可以(并且确实)假设this
始终为非空。
但在实际代码中,有时您会不小心这样做。通常,它没有任何不良影响,当然除了this
方法中为 null,并且事情可能会崩溃。
作为调试辅助工具,并本着尽早崩溃的精神,我把assert(this != 0)
在我之前几次不小心调用空指针的方法中。它似乎有效,但 clang 抱怨:
warning: 'this' pointer cannot be null in well-defined C++ code; comparison may be
assumed to always evaluate to true [-Wtautological-undefined-compare]
assert (this ! = 0);
^~~~ ~
我想知道最好的(最不正确的)方法是什么来检测这个this
一片空白。可以优化简单的比较。
- 我可以做一些指针算术
this
试图欺骗编译器,或者强制它将指针视为整数。
- 我可以用
memcmp
.
- 也许有特定于编译器的扩展来表示“不要优化这个表达式”?
另一个问题是,在继承的情况下,“空”this 指针实际上可能类似于0x00000004
,所以最好也处理这种情况。我对 Clang、MSVC 或 GCC 的解决方案感兴趣。
在 gcc 中你可以构建-fsanitize=null
。 Clang 也应该有这个选项。
From man gcc
:
-fsanitize=null
This option enables pointer checking. Particularly, the application built with this option turned on will issue an error message when it tries to dereference a NULL pointer, or if a
reference (possibly an rvalue reference) is bound to a NULL pointer, or if a method is invoked on an object pointed by a NULL pointer.
这是一个测试程序:
[ ~]$ cat 40783056.cpp
struct A {
void f() {}
};
int main() {
A* a = nullptr;
a->f();
}
[ ~]$ g++ -fsanitize=null 40783056.cpp
[ ~]$
[ ~]$ ./a.out
40783056.cpp:7:7: runtime error: member call on null pointer of type 'struct A'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)