c++ – Write a wrapper for working with file handles (analogous to auto_ptr but for handles)

Question:

I wrote a simple code like this:

class FileHandleGuard
{
private:
    HANDLE hFile;
public:
    FileHandleGuard(char* fileName) {
        hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL,  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,  NULL);  
    }
    FileHandleGuard(const FileHandleGuard& other) {
        this->hFile = other.hFile;
    }
    ~FileHandleGuard() {
        if (hFile != INVALID_HANDLE_VALUE)
            CloseHandle(hFile);
    }
};

void g(FileHandleGuard f) {
    cout << "g " << endl;
    //вот тут происходит ошибка в деструкторе
}
void someFunction() {
    FileHandleGuard fileHandle("D://myfile.txt");
    g(fileHandle);
}
int main() {
    someFunction();
    system("pause");
    return 0;
}

When passed to function g my smart pointer should behave the same as auto_ptr , i.e. when passed to the function – only this function owns the object and the function that passed it no longer owns At the moment, I get the error: 0xC0000008: An invalid handle was specified .

The original problem statement is written in the title of the question. And is it generally correct that I use the Handle from the windows.h library?

Answer:

You yourself wrote that when passing to a function (read – copying), ownership is transferred, so

FileHandleGuard(const FileHandleGuard& other) {
    this->hFile = other.hFile;
}

needs to be rewritten as

FileHandleGuard(FileHandleGuard& other) {
    this->hFile = other.hFile;
    other.hFile = INVALID_HANDLE_VALUE;
}

By the way, you need to write the assignment operator accordingly …

Scroll to Top