I found one more case when compiler thinks that static_cast
may return nullptr on non-nullptr argument. It seems that this time there is no undefined behavior, like was before, but maybe I'm missing something.
Here's the code compiled with gcc with -O1 -fPIC -Wnull-dereference -Werror
options:
struct IR {
virtual ~IR() = default;
};
struct IF {
virtual ~IF() = default;
virtual void get() {};
};
struct SC : IR, IF {
bool h(); // { return true; };
};
struct HD : public IR {
virtual void g() {
if (r_ && r_->h()) {
static_cast<IF*>(r_)->get();
}
}
SC* r_ = nullptr;
};
bool SC::h() { return true; }
HD hd;
Any one of the following conditions will eliminate potential null pointer dereference
warning:
- making
SC::h()
inline; - making
IF::get()
non-virtual; - changing optimization level from
-O1
to-O0
; - removing
-fPIC
option...
So, is there a GCC bug, or still UB in code, or static_cast
for non-nullptr can results in nullptr?
Link to godbolt.