constructing string from NULL?

dar*_*une 7 c++ string c++17

After some change of the code-base I came accross this gotcha:

#include <string>

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

int main()
{
    test(NULL);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/7uJnef

This throws an exception. Changing to 'nullptr' helps nothing (still no error or warning).

I guess my question is, is there a way to detect or find this error at pre-runtime throughout the sourcecode ? perhaps some compiler warning, etc. (using MSVC VS-2017)

I ended up modifying the basic_string template ala. basic_string(int) = delete; basic_string(::std::nullptr_t) = delete; - this won't catch all cases but does indeed seem to catch the direct cases at least

lub*_*bgr 4

cppcheck在示例文件上运行(版本 1.89)会产生:

Checking test.cpp ...
test.cpp:9:10: error: Null pointer dereference [nullPointer]
test(NULL);
     ^
Run Code Online (Sandbox Code Playgroud)

  • @VTT 我认为他们尝试大致更新(不知道 C++17,但 C++11 基础知识应该没问题),但我想手动指定要运行的测试可能是可行的方法。 (2认同)