在尝试用C++方法封装C API时,发现抛出异常的问题:
int status;
char* log = nullptr;
int infoLogLength;
getFooStatus(&status);
getFooLogLength(&infoLogLength);
if (!status) {
log = new char[infoLogLength];
getFooLog(infoLogLength, log);
throw std::runtime_error(log);
}
不允许我以任何方式修改接口(interface)方法。
据我了解,我需要为要填充的方法保留内存,并对其进行操作。但是,抛出异常将从该方法返回,而不是让我释放资源。我的代码是否正确,或者我应该以其他方式解决这个问题?
最佳答案
std:runtime_error
需要一个 std::string
,所以给它一个 std::string
而不是 char*
:
int status;
getFooStatus(&status);
if (!status) {
int infoLogLength;
getFooLogLength(&infoLogLength);
std::string log(infoLogLength, '\0');
getFooLog(infoLogLength, &log[0]);
throw std::runtime_error(log);
}
或者,您可以传递一个char*
,简单地以促进自动释放的方式分配它,例如:
int status;
getFooStatus(&status);
if (!status) {
int infoLogLength;
getFooLogLength(&infoLogLength);
std::vector<char> log(infoLogLength);
getFooLog(infoLogLength, &log[0]);
throw std::runtime_error(&log[0]);
}
关于c++ - 抛出异常时如何安全地处理数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22774277/