Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use RAII in C++ to prevent resource leakage

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to use RAII in C++ to prevent resource leakage, for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Reason (reason)

Leaks are typically unacceptable. Manual resource release is error-prone. RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks.

Resource leaks are usually unacceptable. Manually releasing resources can easily lead to errors. RAII ("Resource request is initialization") is the easiest and more systematic way to prevent leaks.

Example (sample)

Void F1 (int I) / / Bad: possible leak

{

Int* p = new int [12]

/ /...

If (I < 17) throw Bad {"in f ()", I}

/ /...

}

We could carefully release the resource before the throw:

Before throwing an exception, we must release resources carefully:

Void f2 (int I) / / Clumsy and error-prone: explicit release

{

Int* p = new int [12]

/ /...

If (I < 17) {

Delete [] p

Throw Bad {"in f ()", I}

}

/ /...

}

This is verbose. In larger code with multiple possible throws explicit releases become repetitive and error-prone.

The code is lengthy. On a larger scale, there is more possibility of throwing exceptions, showing that releasing resources is more complex and error-prone.

Void f3 (int I) / / OK: resource management done by a handle (but see below)

{

Auto p = make_unique (12)

/ /...

If (I < 17) throw Bad {"in f ()", I}

/ /...

}

Note that this works even when the throw is implicit because it happened in a called function:

It is important to note that this code still works even if it is implicitly thrown (because it occurs in the called function).

Void f4 (int I) / / OK: resource management done by a handle (but see below)

{

Auto p = make_unique (12)

/ /...

Helper (I); / / may throw

/ /...

}

Unless you really need pointer semantics, use a local resource object:

Unless you really need pointer semantics, use a local resource object:

Void f5 (int I) / / OK: resource management done by local object

{

Vector v (12)

/ /...

Helper (I); / / may throw

/ /...

}

That's even simpler and safer, and often more efficient.

This is simpler, safer, and even more efficient.

Note (Note)

If there is no obvious resource handle and for some reason defining a proper RAII object/handle is infeasible, as a last resort, cleanup actions can be represented by a final_action object.

If there is no obvious resource handle and for some reason it is not feasible to define an appropriate RAII object / handle, as the best means, you can implement the cleanup action through a final_actrion object.

Note (Note)

But what do we do if we are writing a program where exceptions cannot be used? First challenge that assumption; there are many anti-exceptions myths around. We know of only a few good reasons:

But what should we do if we are writing a program and cannot use exception handling? First of all, challenge this assumption; there are many myths against the use of exceptions. We only know that there are very few legitimate reasons:

We are on a system so small that the exception support would eat up most of our 2K memory.

The system you are working on is so small that supporting exceptions will eat up to 2K of memory (unbearable).

We are in a hard-real-time system and we don't have tools that guarantee us that an exception is handled within the required time.

We are in a hard real-time system, and there is no tool to guarantee that exception handling will be completed within the required time.

We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.

We are in a system that contains tons of legacy code that makes heavy use of pointers in incomprehensible ways (usually without an identifiable ownership policy), so exceptions can cause leaks.

Our implementation of the C++ exception mechanisms is unreasonably poor (slow, memory consuming, failing to work correctly for dynamically linked libraries, etc.). Complain to your implementation purveyor; if no user complains, no improvement will happen.

The C++ implementation in use has an unimaginably poor exception mechanism (slow, consuming too much memory, not working with dynamic-link libraries, etc.). Complain about your provider; if there are no user complaints, there will be no improvement.

We get fired if we challenge our manager's ancient wisdom.

If we challenge the stereotyped experience of managers, we will be fired.

Only the first of these reasons is fundamental, so whenever possible, use exceptions to implement RAII, or design your RAII objects to never fail. When exceptions cannot be used, simulate RAII. That is, systematically check that objects are valid after construction and still release all resources in the destructor. One strategy is to add a valid () operation to every resource handle:

Only the first of these reasons is fundamental, so use exceptions to implement RAII whenever possible, or design your own RAII object to ensure that it never fails. If an exception cannot be used, mimic the action of RAII. That is, all resources are released when systematically checking the validity and destructing of the object after it is built. One strategy is to add a valid operation to each resource handle.

Void f ()

{

Vector vs; / / not std::vector: valid () added

If (! vs.valid ()) {

/ / handle error or exit

}

Ifstream fs ("foo"); / / not std::ifstream: valid () added

If (! fs.valid ()) {

/ / handle error or exit

}

/ /...

} / / destructors clean up as usual

This is the answer to the question about how to use RAII in C++ to prevent resource leakage. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 263

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report