Click here to Skip to main content
15,881,860 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 62K   524   59  
Implement a simple-look substitution of BOOST_SCOPE_EXIT using some of the new features of C++0x
// New exception free version of SCOPE_EXIT.

#pragma once

#include <utility>

template <typename D>
class scope_exit_t
{
public:
    explicit scope_exit_t(D &&f) : func(f) {}
    scope_exit_t(scope_exit_t &&s) : func(s.func) {}

    ~scope_exit_t() { func(); }

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

    // Prohibit copying.
    scope_exit_t(const scope_exit_t&) = delete;
    scope_exit_t& operator=(const scope_exit_t&) = delete;

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

    const D func;
};

struct scope_exit_helper
{
    template <typename D>
    scope_exit_t<D> operator << (D &&f) {
        return scope_exit_t<D>(std::forward<D>(f));
    }
};

#define SCOPE_EXIT_CAT2(x, y) x##y
#define SCOPE_EXIT_CAT1(x, y) SCOPE_EXIT_CAT2(x, y)
#define SCOPE_EXIT auto SCOPE_EXIT_CAT1(scope_exit_, __COUNTER__) \
    = scope_exit_helper() << [&]

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