我正在处理旧代码,其中有很多行,例如:
EST_Item_Content *contents() const { return (this == 0) ? 0 : p_contents;}
编译此类函数时,clang 警告:
warning: 'this' pointer cannot be null in well-defined C++ code; comparison may be assumed to always evaluate to false [-Wtautological-undefined-compare]
警告是正确的,但代码not“定义明确”并且检查是必不可少的...
然而,很明显,检查被优化掉了,代码在运行时崩溃了。这是示例 gdb-session:
Program terminated with signal SIGSEGV, Segmentation fault.
Address not mapped to object.
#0 EST_Item::contents (this=0x0) at ../include/ling_class/EST_Item.h:238
238 EST_Item_Content *contents() const { return (this == 0) ? 0 : p_contents;}
(gdb) p this
$1 = (const EST_Item *) 0x0
在没有
-O2
的情况下构建时,检查仍然存在,并且代码可以像多年来一样工作。
我如何告诉 clang not 优化掉这些它认为多余的检查?必须有一些
-f
-flag...
旗帜是
-fno-delete-null-pointer-checks
.