Access Violation when sending a 0 int literal to a const string parameter

前端 未结 2 2043
清歌不尽
清歌不尽 2021-01-08 00:05

On VS2015 and VS2017, this compiles with no warning, and generates an access violation that cannot be caught and crashes the application. Obviously the int 0 is silently con

2条回答
  •  不思量自难忘°
    2021-01-08 00:34

    For this specific case, you can get a compile time error by using C++11 std::nullptr_t, just add the following deleted overload:

    void crash(std::nullptr_t) = delete;
    

    Of course, this won't protect you against passing null (or non-null-terminated ) char* pointers ... you are violating an std::string constructor precondition, resulting in undefined behavior; this is by definition unrecoverable.

    Alternatively, if you really need to catch these errors at runtime in a possibly recoverable way, you could write a const char* overload that throws if given a null pointer or invokes the std::string const& version otherwise.

    If your real function takes more than a few string arguments, and overloading all possible combinations seems not feasible, you could resort writing a function template, performing all the checks over the deduced types ex-post.

提交回复
热议问题