Personal understanding of the concept of "handle"

The word "handle" is translated from "handle". This word should be used as a noun rather than a verb in programming. In English, handle as a noun means "xxx handle / xxx handle". In programming, handle is often used for resources Management, resource handle/resource handle, can be understood as holding the handle/handle to control the resource, through the handle to control the resource, C++ is an object-oriented language, in C++, the handle can be understood as a resource management Object.

Chapter 13.3 of "C++ Programming Language 4th Edition" gives an example, which is roughly like this:

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    QFile f("d://测试.txt");
    f.open(QFile::ReadOnly);
    QByteArray array = f.readAll();
    debug QString(array);
    //......其他操作
    f.close();
}

This code looks very simple, but if an exception is thrown to interrupt the program when performing other operations, the resources acquired by the program will not be released. One way to deal with this problem is to use an exception handling mechanism to release resources when handling exceptions, and another way is to use resource handles.

The specific operation is to define a local class, manage resources in the local class, apply for resources in the constructor, and release resources in the destructor. For objects in the stack memory, even if an exception occurs and the program is interrupted, the analysis of the object will be called Constructor. This ensures that resources will be released.

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    class FileHander
    {
    public:
        FileHander(const QString & filePath)
        {
            file = new QFile(filePath);
            if(!file->open(QFile::ReadOnly))
            {
                debug "打开文件失败";
            }
        }
        ~FileHander()
        {
            if(file)
            {
                if(file->isOpen())
                {
                    file->close();
                }
                file->deleteLater();
                debug "FileHander 释放资源";
            }
        }
        QByteArray getFileAllData()
        {
            if(!file || !file->isOpen())
            {
                return QByteArray();
            }

            return file->readAll();
        }
    private:
        QFile * file{nullptr};
    };

    FileHander fhander("d://测试.txt");
    QByteArray array2 = std::move(fhander.getFileAllData());
    debug QString(array2);
}

The local class FileHander here acts as a handle. The use of resources is done through FileHander, and resources are requested/released in the constructor/destructor.

Guess you like

Origin blog.csdn.net/kenfan1647/article/details/114074778