Why doesn't GCC optimize out deletion of null pointers in C++? -
consider simple program:
int main() { int* ptr = nullptr; delete ptr; }
with gcc (7.2), there call
instruction regarding operator delete
in resulting program. clang , intel compilers, there no such instructions, null pointer deletion optimized out (-o2
in cases). can test here: https://godbolt.org/g/jmdoji.
i wonder whether such optimization can somehow turned on gcc? (my broader motivation stems problem of custom swap
vs std::swap
movable types, deletion of null pointers can represent performance penalty in second case; see https://stackoverflow.com/a/45689282/580083 details.)
update
to clarify motivation question: if use delete ptr;
without if (ptr)
guard in move assignment operator , destructor of class, std::swap
objects of class yields 3 call
instructions gcc. might considerable performance penalty, e.g., when sorting array of such objects.
moreover, can write if (ptr) delete ptr;
everywhere, wonder, whether cannot performance penalty well, since delete
expression needs check ptr
well. but, here, guess, compilers generate single check only.
also, possibility call delete
without guard , surprise me, yield different (performance) outcomes.
update
i did simple benchmark, namely sorting objects, invoke delete
in move assignment operator , destructor. source here: https://godbolt.org/g/7zguvo
running times of std::sort
measured gcc 7.1 , -o2
flag on xeon e2680v3:
there bug in linked code, compares pointers, not pointed values. corrected results follows:
- without
if
guard:17.6 [s]40.8 [s], - with
if
guard:10.6 [s]31.5 [s], - with
if
guard , customswap
:10.4 [s]31.3 [s].
these results absolutely consistent across many runs minimal deviation. performance difference between first 2 cases significant , wouldn't "exceedingly rare corner case" code.
according c++14 [expr.delete]/7:
if value of operand of delete-expression not null pointer value, then:
- [ ...omitted... ]
otherwise, unspecified whether deallocation function called.
so both compilers comply standard, because it's unspecified whether operator delete
called deletion of null pointer.
note godbolt online compiler compiles source file without linking. compiler @ stage must allow possibility operator delete
replaced source file.
as speculated in answer -- gcc may angling consistent behaviour in case of replacement operator delete
; implementation mean can overload function debug purposes , break on invocations of delete
expression, when happened deleting null pointer.
updated: removed speculation might not practical issue, since op provided benchmarks showing in fact is.
Comments
Post a Comment