c++ - 抛出异常时如何安全地处理数组指针

标签 c++ exception

在尝试用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/

相关文章:

python - 在析构函数中创建检查类型映射

c++ - 为什么我听到这个程序发出哔哔声?

c++ - while(fin>>a) 或 while(fin.eof()) 将不起作用。在第一种情况下,fin 流变量一直将文件中的最后一个字符作为输入

c++ - 默认按钮只工作一次

php - 为什么 PHP Solr 扩展给出异常 "Unsuccessful query request"

python - 当我捕捉到异常时,如何获取上一帧的类型、文件和行号?

Java 在类内部定义自定义异常,这不好吗?

c++ - 库达错误 : unexpected launch failure

java - 奇怪的 java.lang.ArrayIndexOutOfBoundsException : -1

exception - 你能捕获异常处理过程中抛出的异常吗?