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 realize the defer function of Go by C++

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "how C++ realizes the defer function of Go". In the operation of actual cases, many people will encounter such a dilemma, so 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!

There is a keyword in the Goto language: defer, which is used to delay the execution of the following function, which is especially useful in resource release, such as the following sample code of Cripple +:

Void test () {FILE* fp = fopen ("test.txt", "r"); if (nullptr = = fp) return; if (...) {fclose (fp); return;} if (...) {fclose (fp); return } if (...) {fclose (fp); return;} fclose (fp);}

Fclose needs to be called to close the file handle before returning everywhere, and the more interruptions in the middle of the process, the easier it is to miss the call to fclose, resulting in a failure to close the file properly.

C++ can use smart pointers such as shared_ptr,auto_ptr to manage the allocated memory, but C++ doesn't have ready-made code to handle it in a situation like this. The Go language provides the defer keyword to solve such problems, and Go can be written as follows:

Func test () {file, err: = os.Open ("test.txt") if err! = nil {return} defer file.Close () if... {return} if... {return} if. {return}}

You only need to use one sentence:

Defer file.Close ()

Then, Go will automatically call the function after defer after return. Let's take a look at the following example:

Package mainimport ("fmt") func test () (n int, err error) {defer fmt.Println ("Test 1") defer fmt.Println ("Test 2") defer fmt.Println ("Test 3") return fmt.Println ("test")} func main () {test ()}

Its output is:

Test

Test 3

Test 2

Test 1

You can see that when there is more than one defer, it is executed in a first-in-and-out manner.

In C++, we can use destructors to achieve, and C++ 's local variable destructor rules are also implemented in a first-in-first-out way. To do this, we need to define a Defer class:

# include typedef std::function fnDefer;class Defer {public: Defer (fnDefer fn): m_fn (fn) {} ~ Defer () {if (m_fn) m_fn ();} private: fnDefer massifn;}

In this way, the previous C++ sample code can be written as follows:

Void test () {FILE* fp = fopen ("test.txt", "r"); if (nullptr = = fp) return; Defer d ([&] () {fclose (fp);}); if (...) {return } if (...) {return;} if (...) {return;}}

You no longer have to manually write code to close the file before returning to every place.

But there is another inconvenience here is the need to hand-write a lambda expression and manually define a variable, which is easy to solve, using macros to deal with.

# define defer1 (AMaginb) a##b#define defer2 (aMagneb) defer1 (aMagneb) # define defer (expr) Defer defer2 (_ _ Defer__,__COUNTER__) ([&] () {expr;})

To facilitate the use of the same function in multiple places, the defer macro is defined to give different names to the variable. The previous code can be changed to:

Void test () {FILE* fp = fopen ("test.txt", "r"); if (nullptr = = fp) return; defer (fclose (fp)); if (...) {return;} if (...) {return } if (...) {return;}}

This is practical and much more convenient. The complete code and test cases are given below:

# include using namespace std;typedef std::function fnDefer;class Defer {public: Defer (fnDefer fn): m_fn (fn) {} ~ Defer () {if (m_fn) m_fn ();} private: fnDefer massifn;} # define defer1 (aforme b) a##b#define defer2 (aforme b) defer1 (aforme b) # define defer (expr) Defer defer2 (_ _ Defer__,__COUNTER__) ([&] () {expr;}) class Test {public: void f (int I) {printf ("FRV% d% p", I, this);}}; int main (int argc, char * argv []) {Test t Printf ("test:%p", & t); defer (T.F (1)); defer (T.F (2)); defer (T.F (3)); return 0;}

The results are as follows:

This is the end of the introduction of "how C++ implements the defer function of Go". Thank you for 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!

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: 0

*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