This is sort of the complementary question to How to best protect from 0 passed to std::string parameters?. Basically, I'm trying to figure out whether there is a way to have the compiler warn me if a code path would unconditionally try to call std::string
's char*
constructor using NULL
.
Run time checks are all well and good, but for a case like:
std::string get_first(const std::string& foo) {
if (foo.empty()) return 0; // Or NULL, or nullptr
return foo.substr(0, 1);
}
it's annoying that, even though the code is guaranteed to fail if that code path is exercised, and the system header is usually annotated with the precondition saying that the pointer must not be null, this still passes compilation under gcc
, clang
, etc., even with -std=c++11 -Wall -Wextra -pedantic -Werror
. I can block the specific case of 0
on gcc
with -Werror=zero-as-null-pointer-constant
, but that doesn't help with NULL
/nullptr
and it's sort of tackling the related but dissimilar problem. The major issue is that a programmer can make this mistake with 0
, NULL
or nullptr
and not notice it if the code path isn't exercised.
Is it possible to force this check to be compile time, covering an entire code base, without nonsense like replacing std::string
with a special subclass throughout the code?
string
's requirements). You can't really hope for a guarantee of...anything after that. As far as I can see, nearly the only reasonable approach is to ensure against that happening in the first place.0
/NULL
/nullptr
, we're invoking said behavior so directly that compilers with headers that mention the restriction should be able to see that we've violated the constraints of the function. I'm sort of hoping the compiler can catch the problem before we actually run and invoke said undefined behavior.std::string
for constructors takingnullptr_t
andint
parameters in place ofcharT const *
. It would at least be easy to make these fail "fast and noisy", such as throwingstd::invalid_argument
from the ctor, so no other code could ever see such a string. OTOH,string
already has lots of constructors, so it would take some care to be sure these couldn't be invoked for valid inputs. Thenullptr_t
overload should be safe though.