指针和虚函数表

C++ 的 ScopeExitGuard

輝夜(tadvent) posted @ 2014年12月12日 15:18 in C/C++ with tags c++ , 3536 阅读

C++ 提供了 RAII 机制,并提倡使用它来管理各种资源,可是在实际中会发现这一套使用起来并不如想象中的那么方便。在 Linux 下开发会遇到大量 open() / close() 或是 malloc() / free() 类似操作,而且大部分都没有现成好用的 C++ wrapper,如果每组操作都自己去寨一个 class OperationGuard 只用来管理资源释放未免又显得过于繁琐。

其实我需要的只是在退出作用域时自动执行一些清理操作,如果能方便的把要进行的操作封装在一个临时对象的析构函数里就好了。在网上搜索了一下,果然已经有 很多人想到了这个问题,现成的实现有 Boost 的 SCOPE_EXIT,看了一下支持的功能很多,用起来也比想象中复杂了不少。于是还是自己来寨一个好了,也不用很复杂:(以下实现参考了SCOPE(EXIT) IN C++11

template<class F>
class ScopeExitGuard_Impl{
    F _f;
public:
    ScopeExitGuard_Impl(F f) : _f(f) {}
    ~ScopeExitGuard_Impl(){
        _f();
    }
};
template<class F>
ScopeExitGuard_Impl<F> ScopeExitGuard(F f){
    return ScopeExitGuard_Impl<F>(f);
}

#define SCOPE_EXIT_GUARD(code) \
    auto scope_exit_##__LINE__ = ScopeExitGuard([&]{code;})

C++11 的 lambda 真是好用啊。在 SCOPE(EXIT) IN C++11 那篇中,lambda 使用了 [=] 来获取外部变量,这样一来就只能读取,无法改写。我在上面的 lambda 中改为 [&] 方便改写外部变量。

使用起来很简单:

int a = 1;
{
    SCOPE_EXIT_GUARD(a = 2);
    a = 3;
}
cout << a << endl; // print: 2
{
    int *p = (int*)::operator new(100 * sizeof(int));
    // label 1
    SCOPE_EXIT_GUARD(::operator delete(p));
    for (int i = 0; i < 10; ++i){
        p[i] = i;
    }
}

如果在 ::operator new() 语句或 label 1 处抛出异常,::operator delete() 就不会被调用,因此只需把释放资源的 SCOPE_EXIT_GURAD 语句与申请资源的语句放在一起就好。

Multilingual Content 说:
2021年4月04日 09:09

Your blogs further more each else volume is so entertaining further serviceable It appoints me befall retreat encore. I will instantly grab your feed to stay informed of any updates.

UK buiding work pric 说:
2021年4月06日 07:39

You got a very fantastic website, Glad I observed it through yahoo.

where is a pawn shop 说:
2021年4月07日 07:20

Amazing sharing, Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work, I will keep visit here.

Makunudu Isand Maldi 说:
2021年4月09日 00:49

Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for.

allergies 说:
2021年4月10日 12:44

Thank you so much as you have been willing to share information with us

farrar jewelers scot 说:
2021年4月14日 10:04

Wow, What an exceptional pronounce. i found this too much informatics. it's miles what i used to be searching for for. i'd as soon as to area you that absorb keep sharing such kind of data.If realistic, thank you

pawn shop glendale a 说:
2021年5月04日 08:50

This article was written by a real thinking writer. I agree many of the with the solid points made by the writer of

consignment diamonds 说:
2021年5月06日 15:23

Thanks For sharing this Superb article.I use this Article to show my assignment in college.it is useful For me Great Work.

pawn shop glendale a 说:
2021年7月06日 20:31

Wow, What an exceptional pronounce. i found this too much informatics. it's miles what i used to be searching for for. i'd as soon as to area you that absorb keep sharing such kind of data.If realistic, thank you

YOLO 说:
2021年12月07日 19:58

slotxo Football price online Online betting odds

Cyber Security Inter 说:
2022年8月10日 17:10

One thing you should understand is that there is no precise and standalone site where you will be able to find only Cyber Security Internships right away. But we have found some of the best sites online that you will be able to browse to find out the best Internship option for the Cyber Security role. Cyber Security Internships Cyber Security is a broader term coined into to understand the main role of security maintenance of the IT companies when it comes to the Cyber unit, which is the cloud connection.

안전놀이터 说:
2023年1月08日 21:20

christian dating is always exciting and enjoyable, i would really love to day a christian girl-

james 说:
2023年4月06日 15:42

Hey there! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no back up. Do you have any solutions to prevent hackers? rental car in karachi

terapia de pareja 说:
2023年6月25日 22:56

En el ámbito de la terapia psicológica de pareja, así como en el tratamiento individual, también existe la opción de solicitar una terapia de manera online, modalidad que presenta ciertas ventajas que deben ser tenidas en cuenta. Algunas de estas son la mayor flexibilidad de horarios y comodidad, mayor seguridad y anonimato en el paciente a quien le cueste desplazarse hacia una consulta psicológica y casi siempre, un coste de terapia más económico.

SEO 说:
2023年12月03日 21:15

Are you aware of the latest measures to prevent 먹튀 in online betting?

civaget 说:
2023年12月04日 01:13 My revenue has seen a significant boost with 백링크하이's SEO expertise. A wise investment!
civaget 说:
2023年12月07日 23:34

Unwind and have fun at a 유흥사이트 near you. Find the perfect place to relax and enjoy quality entertainment.

civaget 说:
2023年12月10日 23:04

Playing 에볼루션카지노 is an immersive experience. The live blackjack and baccarat are my favorites. It's the epitome of online casino excellence.

civaget 说:
2023年12月12日 18:50

안전카지노's quick deposit and withdrawal process is a game-changer for busy players.

civaget 说:
2023年12月14日 15:05

With 축구중계, you're not just a fan – you're family.

civaget 说:
2023年12月17日 18:35

Discover the power of op사이트 순위 in website selection.

civaget 说:
2023年12月18日 23:25

Joining discussions on 오피 sites is a great way to connect with fellow OP enthusiasts.

seo service london 说:
2023年12月21日 21:51

Hello, i think that i saw you visited my site this i came to “return the favor”.I am trying to find things to enhance my web site! I suppose its ok to use a few of your ideas!!  You’re brilliant! Thank you! I experience the beneficial data you offer for your articles. Fantastic blog! I dont assume ive visible all the angles of this situation the way youve

바나나 이벤트 说:
2023年12月28日 13:53

Once a while, we seem that many love couples, whose relationship works optimally for a few months and years, but sudden some changes occur which is totally unimaginable, in fact, a couple also doesn't even think that about that, such a kind of moment they will ever face in their life. Because sometimes circumstance makes couple life worse and can't get that point. This is the only reason, most love story ends.

구조대 도메인 说:
2023年12月28日 14:37

Wow, cool post. I’d like to write like this too – taking time and real hard work to make a great article… but I put things off too much and never seem to get started. Thanks though.I hope it will be helpful for almost all peoples that are searching for this type of topic. I Think this website is best for such topic. good work and quality of articles

쇼미더벳 이벤트 说:
2023年12月28日 14:47

Now You Can Stop Your Break Up, Divorce or Lovers Rejection… Even If Your Situation Seems Hopeless! My husband said he no longer loved me at the end of January this year and i was hurt and heart broken i felt like my life was about to end and I almost committed suicide, I was emotionally down for a very long time. Thanks to a spell caster called Dr OSCAR DILAN, which I meet online, on one faithful day, as I was browsing through the internet and I came across a lot of testimonies about this particular spell caster. Some people testified that he brought their Ex lover back, some testified that he restores womb, cure cancer and other sickness, some testified that he can cast a spell to stop divorce and so on. I also come across one particular testimony and it was about a woman called Tracey Hilton,

토큰게임있는사이트 说:
2023年12月28日 15:05

Our web design company in Dubai is the leading provider of professional website design, web development, WordPress, Joomla, Magento, website hosting, website maintenance, Graphic Design, digital marketing, and search engine optimization in the UAE to help your business grow. In Dubai, we are the most trusted website design company and digital services agency. Using advanced coding, user-friendly designs, natural navigation, and the latest technology, we craft dynamic and stunning websites for an unparalleled digital experience that inspires and syncs with your customers on any browser and device.

메이저놀이터 说:
2023年12月28日 15:24

Our web design company in Dubai is the leading provider of professional website design, web development, WordPress, Joomla, Magento, website hosting, website maintenance, Graphic Design, digital marketing, and search engine optimization in the UAE to help your business grow. In Dubai, we are the most trusted website design company and digital services agency. Using advanced coding, user-friendly designs, natural navigation, and the latest technology, we craft dynamic and stunning websites for an unparalleled digital experience that inspires and syncs with your customers on any browser and device.

먹튀검증 说:
2023年12月28日 15:32

Factoring some form of working task into the recruitment process has long been a way to assess a candidate’s suitability for a role. Along with being a chance for employers to see how their potential hire would approach aspects of the job, these ‘working interviews’ also enable the candidate to flex their skills, especially if they don’t thrive in the interview hotseat.

메이저사이트 说:
2023年12月28日 15:51

Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written.

안전사이트 검증 说:
2023年12月28日 16:14

It has fully emerged to crown Singapore's southern shores and undoubtedly placed her on the global map of residential landmarks. I still scored the more points than I ever have in a season for GS. I think you would be hard pressed to find somebody with the same consistency I have had over the years so I am happy with that

먹튀와이가입 说:
2023年12月28日 16:23

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work Greetings to each one, it's really a particular for me to visit this website page, it comprises of helpful Information

메이저토토 说:
2023年12月28日 16:30

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work Greetings to each one, it's really a particular for me to visit this website page, it comprises of helpful Information

안전한 바카라 说:
2023年12月28日 16:36

Once a while, we seem that many love couples, whose relationship works optimally for a few months and years, but sudden some changes occur which is totally unimaginable, in fact, a couple also doesn't even think that about that, such a kind of moment they will ever face in their life. Because sometimes circumstance makes couple life worse and can't get that point. This is the only reason, most love story ends.

먹튀슈퍼맨 도메인 说:
2023年12月28日 16:52

The Training is designed as Flexible as to meet the demands of fresher's and working professionals. It offers a number of Advanced & Corporate E-Marketing, Online Marketing and Internet Marketing programs & courses to help you take advantage of and develop your own in-house or personal knowledge base in Website Promotions digital marketing course

먹튀클래스 说:
2023年12月28日 16:57

Wow, cool post. I’d like to write like this too – taking time and real hard work to make a great article… but I put things off too much and never seem to get started. Thanks though.I hope it will be helpful for almost all peoples that are searching for this type of topic. I Think this website is best for such topic. good work and quality of articles

백화점 가입 说:
2023年12月28日 17:04

Now You Can Stop Your Break Up, Divorce or Lovers Rejection… Even If Your Situation Seems Hopeless! My husband said he no longer loved me at the end of January this year and i was hurt and heart broken i felt like my life was about to end and I almost committed suicide, I was emotionally down for a very long time. Thanks to a spell caster called Dr OSCAR DILAN, which I meet online, on one faithful day, as I was browsing through the internet and I came across a lot of testimonies about this particular spell caster. Some people testified that he brought their Ex lover back, some testified that he restores womb, cure cancer and other sickness, some testified that he can cast a spell to stop divorce and so on. I also come across one particular testimony and it was about a woman called Tracey Hilton,

벳샷 사이트 说:
2023年12月28日 17:57

There couple of fascinating points with time in this post but I don’t know if these center to heart. There’s some validity but I am going to take hold opinion until I explore it further. Excellent article , thanks and we want more! Added to FeedBurner likewise

포켓몬 도메인주소 说:
2023年12月28日 18:04

Our web design company in Dubai is the leading provider of professional website design, web development, WordPress, Joomla, Magento, website hosting, website maintenance, Graphic Design, digital marketing, and search engine optimization in the UAE to help your business grow. In Dubai, we are the most trusted website design company and digital services agency. Using advanced coding, user-friendly designs, natural navigation, and the latest technology, we craft dynamic and stunning websites for an unparalleled digital experience that inspires and syncs with your customers on any browser and device.

토토사이트 说:
2023年12月28日 18:06

Now You Can Stop Your Break Up, Divorce or Lovers Rejection… Even If Your Situation Seems Hopeless! My husband said he no longer loved me at the end of January this year and i was hurt and heart broken i felt like my life was about to end and I almost committed suicide, I was emotionally down for a very long time. Thanks to a spell caster called Dr OSCAR DILAN, which I meet online, on one faithful day, as I was browsing through the internet and I came across a lot of testimonies about this particular spell caster. Some people testified that he brought their Ex lover back, some testified that he restores womb, cure cancer and other sickness, some testified that he can cast a spell to stop divorce and so on. I also come across one particular testimony and it was about a woman called Tracey Hilton,

먹튀폴리스 说:
2023年12月28日 18:16

Wow, cool post. I’d like to write like this too – taking time and real hard work to make a great article… but I put things off too much and never seem to get started. Thanks though.I hope it will be helpful for almost all peoples that are searching for this type of topic. I Think this website is best for such topic. good work and quality of articles

파워사다리 说:
2023年12月28日 18:22

Our web design company in Dubai is the leading provider of professional website design, web development, WordPress, Joomla, Magento, website hosting, website maintenance, Graphic Design, digital marketing, and search engine optimization in the UAE to help your business grow. In Dubai, we are the most trusted website design company and digital services agency. Using advanced coding, user-friendly designs, natural navigation, and the latest technology, we craft dynamic and stunning websites for an unparalleled digital experience that inspires and syncs with your customers on any browser and device.

카지노가입쿠폰 说:
2023年12月28日 18:31

According to Jack Ellerby, project officer for Cumbria Dark Skies, fieldwork tracing the impact of light pollution and wildlife tends to fall under the radar, because the effects on animals are more incremental than that of other pollution, such as sewage, oil spills or plastic litter.

토토일보주소 说:
2023年12月28日 18:31

Factoring some form of working task into the recruitment process has long been a way to assess a candidate’s suitability for a role. Along with being a chance for employers to see how their potential hire would approach aspects of the job, these ‘working interviews’ also enable the candidate to flex their skills, especially if they don’t thrive in the interview hotseat.

롤토토사이트추천 说:
2023年12月28日 18:40

Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written.

카지노게임사이트 说:
2023年12月28日 18:48

I love them!!! Let's see if I get excited and prepare them for my son's party tomorrow! At the moment I have already practiced with your super cupcakes, they turned out amazing!!!! I linked you by the way!!! he he! Kisses and enjoy the heat, in Barcelona it is unbearable!!!!!!!!! and to think that a year ago I was giving birth! ahahahaha

먹튀검증커뮤니티 说:
2023年12月28日 18:52

It has fully emerged to crown Singapore's southern shores and undoubtedly placed her on the global map of residential landmarks. I still scored the more points than I ever have in a season for GS. I think you would be hard pressed to find somebody with the same consistency I have had over the years so I am happy with that

메이저사이트 说:
2023年12月28日 18:57

Choose to play online slots with fun playing sites. Have played online slots, enjoyed playing, being attacked, playing and getting real money. And you will get the special that you intend to play. Enter AMB online play. Access to play online I am able to set up my new plan from this submit. It presents in depth data. Thanks for this valuable facts for al

코인카지노가입 说:
2023年12月28日 19:07

Love is indescribable and unreliable, when we fall in love with someone, we get eager to express our love feeling in front of them, which is in our heart. However, some of us can express feeling in front of their desired one, but you know all of us don't have such courage, which can easily confess their feeling, consequence of this; they live life without loved and eager. To keep this thing in mind our Specialist, Pt. Hari OM Shastri ji provides love problems solution.

토토사이트추천 说:
2023年12月28日 19:18

Thank you for sharing this post, I really enjoyed reading every single word. Data Science can be interpreted as an advanced application of Computer Science which has been specially designed to deal with the data analytics applications. By making use of advanced tools and algorithms, Data Science has the power to mine & extract valuable insights which are encrypted inside the data. Thereby, uncovering the hidden patterns & information from the data has become a lot easier. This Data Science Course Training In Hyderabad will help the students gain real-world hands-on insights for handling the real-time industry challenges in this Data Science domain.

คาสิโน 说:
2023年12月28日 19:24

Our Data Science course in Hyderabad will also help in seeking the highest paid job as we assist individuals for career advancement and transformation. We carefully curate the course curriculum to ensure that the individual is taught the advanced concepts of data science.

사설토토 说:
2023年12月28日 19:32

“Bring My Love Back By Islamic Dua & Bring My Love Back By Qurani Dua”Our Islamic Maulana and Alim can give you the most remarkable dua for affection back at whatever point you may require it. The reason behind discussing the dua for your sweetheart back is to get your cherished one back, who has cut off an adoration friendship with you. This dua for my darling back is someone who can't confront partition with their cherish

먹튀검증사이트 说:
2023年12月28日 19:44

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work Greetings to each one, it's really a particular for me to visit this website page, it comprises of helpful Information

안전놀이터 说:
2023年12月28日 19:51

Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work

안전놀이터코드 说:
2023年12月28日 19:59

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work Greetings to each one, it's really a particular for me to visit this website page, it comprises of helpful Information

파라오카지노 说:
2023年12月28日 20:12

According to Jack Ellerby, project officer for Cumbria Dark Skies, fieldwork tracing the impact of light pollution and wildlife tends to fall under the radar, because the effects on animals are more incremental than that of other pollution, such as sewage, oil spills or plastic litter.

먹튀제보 说:
2023年12月28日 20:50

May I simply just say what a comfort to find an individual who actually understands what they're discussing on the web. You certainly realize how to bring an issue to light and make it important. More people really need to look at this and understand this side of your story. It's surprising you're not more popular given that you surely possess the gift.

메이저안전놀이터 说:
2023年12月28日 20:57

May I simply just say what a comfort to find an individual who actually understands what they're discussing on the web. You certainly realize how to bring an issue to light and make it important. More people really need to look at this and understand this side of your story. It's surprising you're not more popular given that you surely possess the gift.

civaget 说:
2023年12月29日 17:39

My 천안휴게텔 experience exceeded expectations. Their professionalism and variety of massages make it an unrivaled choice.

seo service london 说:
2024年1月13日 22:02

I think this is one of the most significant information for me. And i’m glad reading your article

먹튀검증 说:
2024年1月20日 15:05

I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us

1인샵 说:
2024年1月29日 14:10

You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!

무료스포츠중계 说:
2024年1月29日 14:23

Thanks for another wonderful post. Where else could anybody get that type of info in such an ideal way of writing?

먹튀검증 说:
2024年1月29日 14:35

Very good content, really interesting and really helpful, thank you


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter