gpt4 book ai didi

c++ - 安全检查 `this` 是否为空

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:42 26 4
gpt4 key购买 nike

首先,我知道在空指针上调用方法是未定义的行为。我还知道,因为这不应该发生,所以编译器可以(并且确实)假定 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 是否为 null 的最佳(最不正确)方法是什么。可以优化出一个简单的比较。

  • 我可以在 this 上做一些指针运算来试图欺骗编译器,或者强制它把指针当作一个整数。
  • 我可以使用 memcmp
  • 也许有特定于编译器的扩展来说明“不要优化此表达式”?

另一个问题是,在继承的情况下,“null”this 指针实际上可能类似于 0x00000004,因此最好也处理这种情况。我对 Clang、MSVC 或 GCC 的解决方案感兴趣。

最佳答案

在 gcc 中,您可以使用 -fsanitize=null 进行构建。 Clang 也应该有这个选项。

来自 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'

关于c++ - 安全检查 `this` 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40783056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com