[英]Proper implementation of functions with noexcept C++11
Are those functions correctly implementing noexcept
/ throw()
这些功能是否正确实现了
noexcept
/ throw()
void do_something(const std::string s) noexcept{
// do something with no exception
}
do_something("Hello");
"Hello" literal
will create new std::string
object and it might throw an exception. "Hello" literal
将创建新的std::string
对象,并且可能会引发异常。
Is this exception will be thrown outside of the function or inside? 是将此异常抛出到函数外部还是内部?
size_t do_something(const char *s) noexcept{
return strlen(s);
}
do_something(nullptr);
strlen
is chosen because it is legacy C
function and it will crash, because s
is nullprt
. 选择
strlen
是因为它是旧版C
函数,并且会崩溃,因为s
是nullprt
。
However this crash is nothing to do with exceptions. 但是,此崩溃与异常无关。 Is the assumption correct?
这个假设正确吗?
In: 在:
void do_something(const std::string s) noexcept
The argument s
is constructed by the caller. 参数
s
由调用方构造。 That is, if constructing std::string
throws an exception, that exception is thrown before do_something
is called. 也就是说,如果构造
std::string
引发异常,则在调用do_something
之前引发该异常。
strlen
is chosen because it is legacy C function and it will crash, becauses
isnullptr
.选择
strlen
是因为它是旧版C函数,并且会崩溃,因为s
是nullptr
。
Technically, accessing memory through invalid pointers results in undefined behaviour. 从技术上讲,通过无效的指针访问内存会导致未定义的行为。 No C++ exceptions are thrown in such cases and the compiler/run-time are not required to detect that.
在这种情况下,不会引发C ++异常,并且不需要编译器/运行时来检测到。
Unlike Java which throws NullPointerException
. 不像Java会抛出
NullPointerException
。 Those Java checks for null pointers may be cheap, but they are not free. 那些Java检查空指针的方法可能很便宜,但它们并非免费的。
On Linux/Unix you are most likely to get SIGSEGV
signal whose default behavior is to terminate the process. 在Linux / Unix上,您最有可能收到
SIGSEGV
信号,其默认行为是终止进程。 You could install your own signal handler and make it throw a C++ exception, but that would result in even more undefined behaviour. 您可以安装自己的信号处理程序并使其引发C ++异常,但这将导致更加不确定的行为。
So, it is best if it crashed as early and loudly as possible so that the code is fixed. 因此,最好尽早崩溃,以使代码固定。
However this crash is nothing to do with exceptions.
但是,此崩溃与异常无关。 Is the assumption correct?
这个假设正确吗?
Correct, a crash is not an exception. 正确,崩溃也不例外。 A crash can be caused by an exception though.
崩溃可能是由异常引起的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.