constructing string from NULL?

Running cppcheck (version 1.89) on the example file yields:

Checking test.cpp ...
test.cpp:9:10: error: Null pointer dereference [nullPointer]
test(NULL);
     ^

You can add a couple of prohibited overloads capturing use of 0, NULL or nullptr arguments:

void test(int bad_argument) = delete;
void test(::std::nullptr_t bad_argument) = delete;

You can add a trampoline function that checks for NULL pointer at compile (and run) time, if your compiler supports it. For GCC it would look like this:

void test(const std::string& s){

}

void test(const char* ptr  __attribute__((nonnull))) {
    test(std::string(ptr));
}

int main()
{
    test(NULL);
    return 0;
}

The warning you get is:

<source>:13:14: warning: null passed to a callee that requires a non-null argument [-Wnonnull]

    test(NULL);
         ~~~~^

Tags:

C++

String

C++17