c++ - 如何在 except-disabled 构建过程中编译带有异常的 c++ 代码

标签 c++ exception makefile build-process

我们的系统不使用 C++ 异常。最近我正在移植一个使用c++异常的第三方代码,例如,有一些异常 抛出内存分配等。

我可以在不更改“第三方”代码的情况下处理这种情况吗?

最佳答案

为库创建一个包装器,用于捕获库抛出的所有异常。在启用异常的情况下编译库和包装器。使用禁用异常的旧代码中的包装器。这样就不会向禁用异常的代码抛出任何内容。

// third party library
// compiled with exceptions
// may throw
int foo();

// wrapper library
// compiled with exceptions
// may not throw
enum class Error { no_error, code_1, code_2 };

int wrapper_foo(Error& err) {
    try {
         err = Error::no_error;
         return foo();
    } catch(const std::length_error& e) {
        // optionally handle specific exceptions differently
        err = Error::code_1;
        return -1;
    } catch(...) {
        // you must catch all thrown objects
        err = Error::code_2;
        return -1;
    }
}

// legacy code
// compiled without exceptions
void bar() {
    Error err;
    int baz = wrapper_foo(err);
    if(err != Error::no_error) {
        // handle error
    }
}

关于c++ - 如何在 except-disabled 构建过程中编译带有异常的 c++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690710/

相关文章:

C++ : error LNK2019: unresolved external symbol

java.net.ConnectException : Connection refused: connect occured 异常

c++ - 捕获从其参数抛出的函数中的异常

shell - makefile shell 和管道

C++ Makefile 错误 - 没有规则可生成目标 '%.cpp'

c++ - 如何编写智能生成文件?

c++ - 当我可以返回一个指针时,为什么要使用 boost::optional

c++ - 如何在运行时更改 styleSheet 属性?

具有宽松类型要求的 C++17 lambda 捕获

ios - -[PUPhotosGridViewController assetAtIndexPath :] NSRangeException