Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to compress the scope of C++

Shulou Source: shulou.com Published: 2022-06-01 19:28:03 10月03日 Update

This article mainly explains "how to compress the scope of C++". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how C++ compresses the scope".

ES.5: compress scope as much as possible

Reason (reason)

Readability. Minimize the holding time of resources. Avoid misuse of variables.

To put it another way: there is no need to expand the scope of the name.

Example (sample)

Void use ()

{

Int I; / / bad: i is needlessly accessible after loop

For (I = 0; I)

< 20; ++i) { /* ... */ } // no intended use of i here for (int i = 0; i < 20; ++i) { /* ... */ } // good: i is local to for-loop if (auto pc = dynamic_cast(ps)) { // good: pc is local to if-statement // ... deal with Circle ... } else { // ... handle error ... } } Example, bad(反面示例) void use(const string& name) { string fn = name + ".txt"; ifstream is {fn}; Record r; is >

> r

/ /... 200 lines of code without intended use of fn or is...

}

This function is too long by any standard, but the point is that the resources used by fn and is-managed files are maintained for far longer than needed, and it is possible that is and fn will be used unexpectedly in the next part of the function. In this case, it might be a good idea to decompose a read function.

Record load_record (const string& name)

{

String fn = name + ".txt"

Ifstream is {fn}

Record r

Is > > r

Return r

}

Void use (const string& name)

{

Record r = load_record (name)

/ /... 200 lines of code...

} Enforcement (implementation recommendations)

Flag loop variable declared outside a loop and not used after the loop

Marks a situation where a loop variable is defined outside the loop and is no longer used after the loop.

Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)

Mark situations where high-value resources, such as file handles and locks, are not used within N lines (appropriate values).

At this point, I believe you have a deeper understanding of "how C++ compresses the scope". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Functions functions situations resources loops content variables files times tags examples learning practical deeper minimum appropriate necessary unexpected next Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Technology vpn MariaDB Huawei