小编Sas*_*cha的帖子

正确替换C++中缺少的'finally'

由于finally在C++中没有,你必须使用RAII设计模式,如果你希望你的代码是异常安全的.一种方法是使用像这样的本地类的析构函数:

void foo() {
    struct Finally {
        ~Finally() { /* cleanup code */ }
    } finalizer();
    // ...code that might throw an exception...
}
Run Code Online (Sandbox Code Playgroud)

与直接解决方案相比,这是一个很大的优势,因为您不必编写清理代码2次:

try {
    // ...code that might throw an exception...
    // cleanup code (no exception)
} catch (...) {
    // cleanup code (exception)
    throw;
}
Run Code Online (Sandbox Code Playgroud)

本地类解决方案的一大缺点是您无法直接访问清理代码中的局部变量.因此,如果您需要访问它们,它会使您的代码膨胀很多,无论如何:

void foo() {
    Task* task;
    while (task = nextTask()) {
        task->status = running;
        struct Finally {
            Task* task;
            Finally(Task* task) : task(task) {}
            ~Finally() { task->status …
Run Code Online (Sandbox Code Playgroud)

c++ exception finally c++-faq

11
推荐指数
3
解决办法
6769
查看次数

如何获取例外的名称/描述?

如何在不必将字符串硬编码到应用程序中的情况获得SEH异常的名称和/或描述?

我尝试使用FormatMessage(),但它有时会截断消息,即使您指定忽略插入:

__asm { // raise access violation
    xor    eax, eax
    mov    eax, [eax]
}
Run Code Online (Sandbox Code Playgroud)

使用代码引发异常0xC0000005 (EXCEPTION_ACCESS_VIOLATION).

char msg[256];
FormatMessageA(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS,
    GetModuleHandleA("ntdll.dll"), 0xC0000005,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    msg, sizeof(msg), NULL);
Run Code Online (Sandbox Code Playgroud)

填充msg截断的字符串:" The instruction at 0x".

windows winapi exception

8
推荐指数
1
解决办法
1035
查看次数

标签 统计

exception ×2

c++ ×1

c++-faq ×1

finally ×1

winapi ×1

windows ×1