Why should the explicitly assigned resources be immediately handed over to the resource management object in C++?
This article introduces the knowledge of why explicitly allocated resources are immediately handed over to resource management objects in C++. Many people will encounter this dilemma in the operation of actual cases. then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!
R.12: immediately hand over explicitly allocated resources to resource management objects
Reason (reason)
If you do not do so, a leak may occur when an exception occurs or when a return operation occurs.
Example, bad (negative example)
Void f (const string& name)
{
FILE* f = fopen (name, "r"); / / open the file
Vector buf (1024)
Auto _ = finally ([f] {fclose (f);}); / / remember to close the file
/ /...
}
Failure to allocate buffer (throw exception, translator's note) will cause the file handle to leak.
Example (sample)
Void f (const string& name)
{
Ifstream f {name}; / / open the file
Vector buf (1024)
/ /...
}
(managed with ifstream) the use of file handles is simple, efficient, and secure.
Enforcement (implementation recommendations)
Tag initializes pointers with explicitly allocated resources (the question is: how many cases can we identify when resources are allocated directly?)
This is the end of the content of "Why do you immediately hand over explicitly allocated resources to resource management objects in C++?" Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!