将0 int常量发送给const字符串参数时发生访问冲突 [英] Access Violation when sending a 0 int literal to a const string parameter

查看:50
本文介绍了将0 int常量发送给const字符串参数时发生访问冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VS2015和VS2017上,此编译不会发出警告,并且会生成无法捕获的访问冲突并导致应用程序崩溃.显然,将int 0静默转换为空指针,然后假定该指针指向一个字符串,从而导致崩溃.

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 converted to a null pointer which is then assumed to point to a string hence crashing.

#include <string>
#include <iostream>
void crash(const std::string& s) {}
int main()
{
    try
    {
        crash(0);
    }
    catch (const std::exception& ex)
    {
        // never gets here!
        std::cout << "got" << ex.what() << std::endl;
    }
}

如何捕获此类异常并从中恢复?如果我从函数参数中删除const,它将无法编译-所以这可能是防止用户滥用的一种方法,但是我会失去const提供的保护,或者我会吗?编写避免这种问题的原型的最佳实践是什么?

How can I trap and recover from such an exception? If I drop the const from the function parameter it does not compile - so that's maybe one way to guard from misuse by users, but I would lose the protection provided by the const, or would I? What's the best practice to write prototypes that avoid this problem?

推荐答案

对于这种特定情况,您可以使用C ++ 11 std :: nullptr_t 来获取编译时错误,只需添加以下已删除的重载:

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;

当然,这不会保护您避免传递null(或非null终止的)char *指针……您违反了std :: string构造函数的前提,导致未定义的行为;根据定义,这是无法恢复的.

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.

或者,如果您确实需要在运行时以可能可恢复的方式捕获这些错误,则可以编写 const char * 重载,如果给定空指针或调用 std,则会抛出该重载:: string const& 版本.

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.

如果您的实函数使用多个字符串参数,并且重载所有可能的组合似乎不可行,则可以求助于编写函数模板,对推断出的类型 post-post 进行所有检查

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.

这篇关于将0 int常量发送给const字符串参数时发生访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆