Val*_*lus 1 c++ exception exception-safe exception-safety c-standard-library
在下面的代码中,作者指出new operator函数调用可能会导致异常,因此此实现不是异常安全的,因为对象状态已在第一行中更改。
String &String::operator =( const char *str ) {
// state is changed
delete [] s_;
if( !str ) str = "";
// exception might occur because of new operator
s_ = strcpy( new char[ strlen(str)+1 ], str );
return *this;
}
Run Code Online (Sandbox Code Playgroud)
在阅读时,我想知道 C 库函数会在 C++ 中抛出异常吗?我知道 C 中没有例外,但由于我们使用的是 C++ 编译器,因此可能会有例外。
那么,我们可以将 C 标准库函数视为异常安全的函数调用吗?
谢谢你。
顺便说一句,为了记录,实现上述功能的正确方法(异常安全)如下。
String &String::operator =( const char *str ) {
if( !str ) str = "";
char *tmp = strcpy( new char[ strlen(str)+1 ], str );
delete [] s_;
s_ = tmp;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
在阅读时,我想知道 C 库函数会在 C++ 中抛出异常吗?
如果您正确使用这些功能,则不会。他们怎么可能?这将完全破坏向后兼容性。
但是,如果您不正确地使用它们,则会发生未定义的行为。在这种情况下,编译器可以做任何它想做的事情,包括抛出异常。
例如,下面的程序根据 C++ 语言标准表现出未定义的行为:
#include <iostream>
#include <string.h>
int main()
{
try
{
strcpy(nullptr, nullptr);
}
catch (...)
{
std::cerr << "exception\n";
}
}
Run Code Online (Sandbox Code Playgroud)
使用结构化异常处理使用 Visual C++ 2013 编译它,如下所示:
cl /nologo /Za /EHa /W4 stackoverflow.cpp
Run Code Online (Sandbox Code Playgroud)
程序结果:
exception
Run Code Online (Sandbox Code Playgroud)