Is CreateFile exception safe?

499 Views Asked by At

I am using CreateFile() to open and read a file. If an exception is thrown will the file be closed or do I need to catch it and close the file myself. If the latter is true, what is the best way to catch and close the file. Thanks!

1

There are 1 best solutions below

0
joe_chip On

The file won't be closed. If you want to make sure it is closed, you can wrap it in unique_ptr with custom deleter, like this:

struct HandleDeleter
{
    void operator ()(HANDLE hObject) { CloseHandle(hObject); }
};

using SafeHandle = std::unique_ptr<HANDLE, HandleDeleter>; // for convenience

void someFunction()
{
    // automatically closed at the end of parent scope:
    SafeHandle hFile(CreateFile(...));

    throw std::runtime_error("the file will be closed now");
}