Click here to Skip to main content
15,886,689 members
Articles / Programming Languages / Visual C++ 12.0

Simple-Look Scope Guard for Visual C++ 2010

Rate me:
Please Sign up or sign in to vote.
4.89/5 (42 votes)
18 Jun 2014Public Domain5 min read 62.1K   524   59  
Implement a simple-look substitution of BOOST_SCOPE_EXIT using some of the new features of C++0x
// Boost dependent version of SCOPE_EXIT.

#pragma once

#include <functional>
#include <boost/noncopyable.hpp>
#include <boost/preprocessor.hpp>

class scope_exit_t : private boost::noncopyable
{
    typedef std::function<void()> func_t;

public:
    scope_exit_t(func_t &&f) : func(f) {}
    ~scope_exit_t() { func(); }

private:
    // Prohibit construction from lvalues.
    scope_exit_t(func_t &);

    // Prohibit new/delete.
    void *operator new(size_t);
    void *operator new[](size_t);
    void operator delete(void *);
    void operator delete[](void *);

    const func_t func;
};

#define SCOPE_EXIT scope_exit_t BOOST_PP_CAT(scope_exit_, __COUNTER__) = [&]

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Software Developer
Japan Japan
In 1985, I got my first computer Casio MX-10, the cheapest one of MSX home computers. Then I began programming in BASIC and assembly language, and have experienced over ten languages from that time on.
Now, my primary languages are C++ and C#. Working for a small company in my home town in a rural area of Japan.


Comments and Discussions