离开析构函数的一个例外异常案例

Bil*_*eal 1 c++ destructor exception-handling

我正在研究一个简单的类来管理a的生命周期HKEY.

class Key
{
    HKEY hWin32;
public:
    Key(HKEY root, const std::wstring& subKey, REGSAM samDesired);
    Key(const Key& other);
    ~Key();
    Key& operator=(const Key& other);
    Key& swap(Key& other);
    HKEY getRawHandle() { return hWin32; };
};

 //Other Methods....

Key::~Key()
{
    LONG errorCheck
        = RegCloseKey(hWin32);
    /*
     * I know it's generally bad to allow exceptions to leave destructors,
     * but I feel that if RegCloseKey() is going to fail, the application
     * should be terminated. (Because it should never fail.)
     */
    if (errorCheck != ERROR_SUCCESS)
        WindowsApiException::Throw(errorCheck);
}
Run Code Online (Sandbox Code Playgroud)

这是有道理的推理吗?我不知道如何将失败RegCloseKey()传达给被叫者.

Joh*_*ler 5

RegCloseKey的失败更多的是一种assert情况,而不是需要传递给调用链的错误.你想坐起来,并采取通知马上在调试版本中,

但是失败信息会对调用者有什么好处呢?他该怎么办呢?