What is ScopeGuard in C++? - c++

I am under the impression that it is a C++ class contained in a library written by a third party. I tried searching on Google, and I found one post that said it was a good idea to use it. However, it failed to describe exactly what it is and how I can incorporate it into my code. Thanks.

ScopeGuard was once a particular implementation of scope guards by Petru Marginean and Andrei Alexandrescu. The idea is to let the destructor of a guard object call a user specified cleanup action at the end of a scope (read: block), unless the scope guard is dismissed. Marginean came up with an ingenious idea of declaring a scope guard object for C++03, based on lifetime extension of a reference to const.
Today “scope guard” is more the general idea.
Scope guards are based on RAII (automatic destructor calls used for cleanup), just as e.g. a for loop is based on jumps, but one wouldn't ordinarly call a for loop a jump-based piece of code, because that loses most of the information of what it is about, and likewise one does not ordinarily refer to scope guards as RAII. for loops are at a higher level of abstraction, and are a more specialized concept, than jumps. Scope guards are at a higher level of abstraction, and are a more specialized concept, than RAII.
In C++11 scope guards can be trivially implemented in terms of std::function, with the cleanup action supplied in each place via a lambda expression.
Example:
#include <functional> // std::function
#include <utility> // std::move
namespace my {
using std::function;
using std::move;
class Non_copyable
{
private:
auto operator=( Non_copyable const& ) -> Non_copyable& = delete;
Non_copyable( Non_copyable const& ) = delete;
public:
auto operator=( Non_copyable&& ) -> Non_copyable& = default;
Non_copyable() = default;
Non_copyable( Non_copyable&& ) = default;
};
class Scope_guard
: public Non_copyable
{
private:
function<void()> cleanup_;
public:
friend
void dismiss( Scope_guard& g ) { g.cleanup_ = []{}; }
~Scope_guard() { cleanup_(); }
template< class Func >
Scope_guard( Func const& cleanup )
: cleanup_( cleanup )
{}
Scope_guard( Scope_guard&& other )
: cleanup_( move( other.cleanup_ ) )
{ dismiss( other ); }
};
} // namespace my
#include <iostream>
void foo() {}
auto main() -> int
{
using namespace std;
my::Scope_guard const final_action = []{ wclog << "Finished! (Exit from main.)\n"; };
wcout << "The answer is probably " << 6*7 << ".\n";
}
The rôle of the function here is to avoid templating so that Scope_guard instances can be declared as such, and passed around. An alternative, slightly more complex and with slightly constrained usage, but possibly marginally more efficient, is to have a class templated on a functor type, and use C++11 auto for declarations, with the scope guard instance created by a factory function. Both these techniques are simple C++11 ways to do what Marginean did with reference lifetime extension for C++03.

It's more of a design pattern than a particular class. It is a way of aquiring/releasing resources (such as files, memory, or mutexes) that is exception safe. unique_lock in c++11 follows this pattern.
For example, with unique_lock, instead of writing code like this:
void foo()
{
myMutex.lock();
bar();
myMutex.unlock();
}
You write code like this:
void foo()
{
unique_lock<mutex> ulock(myMutex);
bar();
}
In the first case, what if bar throws an exception? Then, myMutex will never be unlocked, and your program would be left in an invalid state. In the second case, however, unique_lock is programmed to lock the mutex in its constructor, and unlock it in its destructor. Even if bar throws an exception, the unique_lock will be destructed as the stack unwinds when the exception travels upward, and so the lock will be released. This saves you having to wrap every call to bar in a try/catch block and handle exceptions manually.

Related

Long lived objects

I have a class that provides a utility for logging errors and exceptions. This is part of a library that's integrated into other applications. This class is implemented via the Singleton pattern (Meyer's singleton to be specific). The issue arises during the destruction phase when there's no defined point in time when this class is destructed. It so happens that during destruction an error/exception is raised which tries to access this class and leads to undefined behavior. Any flag within the class to maintain its state seemed moot since accessing the flag itself is UB once the object is destructed. I can only think of having the object allocated on the heap and letting it linger till the program execution but an issue with that is instruments designed to detect memory leaks would report this. I've also tried installing an std::atexit() handler but that too was invoked before the destruction of the object which doesn't help. How are such issues of lifetime best handled?
EDIT: Here's a short snippet to illustrate the problem
#include <iostream>
#include <memory>
#define LOG_EXCEPTION(msg) Logger::instance()->logException(msg)
#define LOG_MESSAGE(msg) Logger::instance()->logMessage(msg)
struct Logger {
Logger() = default;
~Logger() {
std::cout<<"~Logger\n";
}
int x;
public:
static const std::shared_ptr<Logger>& instance() {
static auto logger = std::make_shared<Logger>();
return logger;
}
void logException(std::string const& msg) {
++x;
std::cout<<msg<<'\n';
}
void logMessage(std::string const& msg) {
++x;
std::cout<<msg<<'\n';
}
};
struct Foo {
~Foo() {
//Something wrong, so log an exception
LOG_EXCEPTION("oops");
}
};
int main()
{
static Foo f;
LOG_MESSAGE("message"); // Just to force creation of the Logger object
}
As is evident, since Foo f outlives the singleton instance, it is UB to access the Logger instance from its destructor. This is just a demonstrative code but such logging of exceptions can happen at any point in the program sequence and it's difficult to reason about the ordering of the statics (the actual error isn't even from a static instance).
In an overly simplified way that would depend on your code not having other singletons or globals that use in their destructors this Logger you could just:
int main()
{
LOG_MESSAGE("start message"); // Just to force creation of the Logger object
{
static Foo f;
//All the rest of your code here.
}//Everything else is destroyed here.
//This could be a function instead of a block.
}//Logger is destroyed here
But if the preconditions are not met (other globals/singletons) then moving away from the Meyers Singleton will be necessary. A "reviving" singleton or dependency injection as suggested in the comments would be good possibilities.

Proper C++ way of implementing a lock_guard for custom library

O wise interwebs
We have an impasse between two colleagues that we could use your help resolving in the proper C++ way. Basically we have a set of utility classes, two of which are a Mutex and SpinLock class which both have the following abridged interface:
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
// ...
};
Obviously this is similar to, but differently-cased than the BasicLockable concept used by std::lock_guard, so we want something similar (assume that the Mutex class is immutable in this example; we cannot add the BasicLockable concept to it). Also not all of our compilers for supported platforms are fully c++11 featured, so we cannot just use vanilla c++11 support.
One school of thought is the following implementation of a generic guard class which can be inherited to provide a generic guard class and inherit from it to create a lock-guard class:
template<class T, void (T::*EnterFn)(), void (T::*ExitFn)()>
class Guard
{
public: // copy constructor deleting omitted for brevity
Guard( T *lock ) : m_lock(lock) { (m_lock->*EnterFn)(); }
~Guard(); { (m_lock->*ExitFn)(); }
private:
T *m_lock;
};
template<class T>
class LockGuard : public Guard<T, &T::Lock, &T::Unlock>
{
public:
LockGuard(const T* lock) : Guard<T, &T::Lock, &T::Unlock>(lock) {}
};
The other school of thought is to just implement a simple lockguard:
template<class T>
class LockGuard {
T* m_lockable;
public:
LockGuard(const T* lockable) : m_lockable(lockable) { lockable->Lock(); }
~LockGuard() { m_lockable->Unlock(); }
};
Which implementation would you choose and why? What is the most proper C++(03, 11, 14, 17) way of implementing it? Is there any inherent value to having a generic Guard class as described above?
I would not want to use method pointers.
Personally, I'd want to move towards the C++11 standard tools as much as possible. So I'd write an adapter.
template<class T>
struct lock_adapter {
T* t = nullptr;
void lock() { t->Lock(); }
void unlock() { t->Unlock(); }
lock_adapter( T& tin ):t(std::addressof(tin)) {}
// default some stuff if you like
};
template<class T>
struct adapted_unique_lock:
private lock_adapter<T>,
std::unique_lock< lock_adapter<T> >
{
template<class...Args>
adapted_unique_lock(T& t, Args&&...):
lock_adapter<T>(t),
std::unique_lock< lock_adapter<T> >( *this, std::forward<Args>(args)... )
{}
adapted_unique_lock(adapted_unique_lock&&)=delete; // sadly
friend void swap( adapted_unique_lock&, adapted_unique_lock& ) = delete; // ditto
};
now adapted_unique_lock has a restricted set of functionality from a std::unique_lock.
It cannot be moved, as the unique_lock holds a pointer to this inside its implementation and does not reseat it.
Note that the richness of the entire unique_lock constructor set is available.
Functions that return adapted unique locks must store their return values in something like auto&& references until end of scope, and you cannot return them through chains until C++17.
But any code using adapted_unique_lock can be swapped to use unique_lock once T has been changed to support .lock() and .unlock(). This moves your code base towards being more standard C++11, rather than bespoke.
I'll answer the question in your title since nobody else answered it.
According to the docs, lock_guard works on any type that "meets the BasicLockable requirements". BasicLockable only requires two methods, lock() and unlock().
In order to make lock_guard work with a custom library, you need to either add lock() and unlock() methods to the library's mutex class, or wrap it in another class that has lock() and unlock() methods.
You should use those: std::mutex, std::shared_lock, std::unique_lock,
std::timed_mutex, std::shared_mutex, std::recursive_mutex, std::shared_timed_mutex, std::recursive_timed_mutex, std::lock_guard if you actually have C++11 compiler. Otherwise it is more complex, and tag c++11 on question should be removed.
You can't implement spinlock or mutex with C\C++ means, you would need add assembler or intrinsic code - making it non-portable, unless you implement it for each platform - and with many x86-64 C++11 and later compilers you can't do inline assembler.
The main problem you would run into, if you use inherent locking logic is that objects behind mutexes or spinlocks are uncopyable. As soon as you copy it or if you copy defended variable, it stops being locked. Objects that are implementing mutex mechanics are uncopyable too.

C++/pimpl: raw pointer or unique_ptr? What is a better choice?

When you use a unique_ptr<T> for a forward declared type T, the unique_ptr destructor requires the T is complete, but the move assignment operator as well (and reset), according to this table:
https://stackoverflow.com/a/6089065/1794803
So, for your pImpl idiom, to implement it correctly, you have to declare the delete and the move assignment method (which, as side effect, marks them non-inlined):
class impl_t;
class A
{
std::unique_ptr<impl_t> p_impl;
public:
// Implement in A.cpp as A::~A() = default;
~A();
// Implemented in A.cpp as A& operator=(A&&) = default;
A& operator=(A&& he);
};
But, since std::unique_ptr is a RAII-solution for dynamic memory, and you pImpl is already inside a class, and you are forced to write a destructor anyway, isn't it better to just manage a raw pointer, since you class is already a RAII-like from the point of view of p_impl?:
class impl_t;
class A
{
impl_t* p_impl;
public:
~A(); // The destructor must be written anyway.
// The omitted move assignment destructor doesn't cause UB.
};
Isn't that a better solution? (+ defined or delete your own copy/move operator if you want to class is copyable/movable or not; but that is a "conscious choice"; however, don't writting a move assignment for unique_ptr is an error).
Using a unique_ptr only saves you for written a delete p_impl in a destructor that you have to declare anyway.
unique_ptr is an excellent choice for local dynamic objects which will be destructed even in case of exceptions, but for "attributes", you save nothing but the possibility of getting UB if you don't remember you have to rewrite the move assignment operator.
Well, using a std::unique_ptr redeems you from bothering with the explicit delete for the p_impl.
Also it should work well in cases of concurrent access and exceptional cases in the constructor (which doesn't seem to be guaranteed using a raw pointer and new yourself).
std::unique_ptr should be the preferred way for pimpl according. For reference, see Herb Sutter's talk at CppCon16 at around 10mins.
The reason is, it will prevent you from accidently changing your pimpl while maintining RAII.
In the question, the not needing to define a move assignment operator is given as a desired advantage. Below I suggest yet another solution that ‘also’ has this advantage, plus that you don’t need to define the destructor. Still I think the most important advantage of the solution below is that the implementation can now be defined in an anonymous namespace (or unnamed namespace).
The price you have to pay is the declaration of a (reusable) base class: impl_t.
#include <iostream>
#include <memory>
////////////////////////
// a utility impl.h file
struct impl_t
{
virtual ~impl_t() = 0;
};
inline impl_t::~impl_t() {}
///////////////////////
// the a_class.cpp file
class a_class_t
{
std::unique_ptr<impl_t> m_pimpl;
public:
a_class_t();
int a_method(int);
};
///////////////////////
// the a_class.cpp file
namespace { // anonymous
struct a_class_impl_t
: impl_t
{
int a_method(int x)
{
return x + 1;
}
~a_class_impl_t()
{
std::cout << "~a_class_impl_t()\n";
}
};
} // anonymous namespace
int a_class_t::a_method(int x)
{
return dynamic_cast<a_class_impl_t&>(*m_pimpl).a_method(x);
}
a_class_t::a_class_t()
: m_pimpl(std::make_unique<a_class_impl_t>())
{}
////////////////////
// the main.cpp file
int main()
{
a_class_t a_class;
std::cout << a_class.a_method(1) << '\n';
}
And also this solution is best of with a unique_ptr.

How to implement multithread safe singleton in C++11 without using <mutex>

Now that C++11 has multithreading I was wondering what is the correct way to implement lazy initialized singleton without using mutexes(for perf reasons).
I came up with this, but tbh Im not really good at writing lockfree code, so Im looking for some better solutions.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
# include <atomic>
# include <thread>
# include <string>
# include <iostream>
using namespace std;
class Singleton
{
public:
Singleton()
{
}
static bool isInitialized()
{
return (flag==2);
}
static bool initizalize(const string& name_)
{
if (flag==2)
return false;// already initialized
if (flag==1)
return false;//somebody else is initializing
if (flag==0)
{
int exp=0;
int desr=1;
//bool atomic_compare_exchange_strong(std::atomic<T>* obj, T* exp, T desr)
bool willInitialize=std::atomic_compare_exchange_strong(&flag, &exp, desr);
if (! willInitialize)
{
//some other thread CASed before us
std::cout<<"somebody else CASed at aprox same time"<< endl;
return false;
}
else
{
initialize_impl(name_);
assert(flag==1);
flag=2;
return true;
}
}
}
static void clear()
{
name.clear();
flag=0;
}
private:
static void initialize_impl(const string& name_)
{
name=name_;
}
static atomic<int> flag;
static string name;
};
atomic<int> Singleton::flag=0;
string Singleton::name;
void myThreadFunction()
{
Singleton s;
bool initializedByMe =s.initizalize("1701");
if (initializedByMe)
s.clear();
}
int main()
{
while (true)
{
std::thread t1(myThreadFunction);
std::thread t2(myThreadFunction);
t1.join();
t2.join();
}
return 0;
}
Note that clear() is just for testing, real singleton wouldnt have that function.
C++11 removes the need for manual locking. Concurrent execution shall wait if a static local variable is already being initialized.
§6.7 [stmt.dcl] p4
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
As such, simple have a static function like this:
static Singleton& get() {
static Singleton instance;
return instance;
}
This will work all-right in C++11 (as long as the compiler properly implements that part of the standard, of course).
Of course, the real correct answer is to not use a singleton, period.
Maybe the easiest way to implement a singleton using C++11 is:
WARNING: Although this works according to the C++11 standard (static initialisers are thread-safe), this is not implemented correctly in Microsoft Visual C++ 2012 (static initialisers are NOT thread-safe). If you are targeting VC2012, then you have to use a different approach, as it does not fully implement the C++11 standard.
class Singleton {
public:
static Singleton& Instance() {
// Since it's a static variable, if the class has already been created,
// it won't be created again.
// And it **is** thread-safe in C++11.
static Singleton myInstance;
// Return a reference to our instance.
return myInstance;
}
// delete copy and move constructors and assign operators
Singleton(Singleton const&) = delete; // Copy construct
Singleton(Singleton&&) = delete; // Move construct
Singleton& operator=(Singleton const&) = delete; // Copy assign
Singleton& operator=(Singleton &&) = delete; // Move assign
// Any other public methods.
protected:
Singleton() {
// Constructor code goes here.
}
~Singleton() {
// Destructor code goes here.
}
// And any other protected methods.
}
IMHO, the best way to implement singletons is with a "double-check, single-lock" pattern, which you can implement portably in C++ 11:
Double-Checked Locking Is Fixed In C++11
This pattern is fast in the already-created case, requiring only a single pointer comparison, and safe in the first-use case.
As mentioned in previous answer, C++ 11 guarantees construction-order safety for static local variables Is local static variable initialization thread-safe in C++11? so you are safe using that pattern. However, Visual Studio 2013 does not yet support it :-( See the "magic statics" row on this page, so if you are using VS2013 you still need to do it yourself.
Unfortunately, nothing is ever simple. The sample code referenced for the pattern above cannot be called from CRT initialization, because the static std::mutex has a constructor, and is thus not guaranteed to be initialized before the first call to get the singleton, if said call is a side-effect of CRT initialization. To get around that, you have to use, not a mutex, but a pointer-to-mutex, which is guaranteed to be zero-initialized before CRT initialization starts. Then you would have to use std::atomic::compare_exchange_strong to create and use the mutex.
I am assuming that the C++ 11 thread-safe local-static-initialization semantics work even when called during CRT initialization.
So if you have the C++ 11 thread-safe local-static-initialization semantics available, use them. If not, you have some work to do, even moreso if you want your singleton to be thread-safe during CRT initialization.
template<class T>
class Resource
{
Resource<T>(const Resource<T>&) = delete;
Resource<T>& operator=(const Resource<T>&) = delete;
static unique_ptr<Resource<T>> m_ins;
static once_flag m_once;
Resource<T>() = default;
public :
virtual ~Resource<T>() = default;
static Resource<T>& getInstance() {
std::call_once(m_once, []() {
m_ins.reset(new Resource<T>);
});
return *m_ins.get();
}
};
It is hard to read your approach as you are not using the code as intended... that is, the common pattern for a singleton is calling instance() to get the single instance, then use it (also, if you really want a singleton, no constructor should be public).
At any rate, I don't think that your approach is safe, consider that two threads try to acquire the singleton, the first one that gets to update the flag will be the only one initializing, but the initialize function will exit early on the second one, and that thread might proceed to use the singleton before the first thread got around to complete initialization.
The semantics of your initialize are broken. If you try to describe / document the behavior of the function you will have some fun, and will end up describing the implementation rather than a simple operation. Documenting is usually a simple way to double check a design/algorithm: if you end up describing how rather than what, then you should get back to design. In particular, there is no guarantee that after initialize completes the object has actually been initialized (only if the returned value is true, and sometimes if it is false, but not always).
#pragma once
#include <memory>
#include <mutex>
namespace utils
{
template<typename T>
class Singleton
{
private:
Singleton<T>(const Singleton<T>&) = delete;
Singleton<T>& operator = (const Singleton<T>&) = delete;
Singleton<T>() = default;
static std::unique_ptr<T> m_instance;
static std::once_flag m_once;
public:
virtual ~Singleton<T>() = default;
static T* getInstance()
{
std::call_once(m_once, []() {
m_instance.reset(new T);
});
return m_instance.get();
}
template<typename... Args>
static T* getInstance2nd(Args&& ...args)
{
std::call_once(m_once, [&]() {
m_instance.reset(new T(std::forward<Args>(args)...));
});
return m_instance.get();
}
};
template<typename T> std::unique_ptr<T> Singleton<T>::m_instance;
template<typename T> std::once_flag Singleton<T>::m_once;
}
This version complies to be concurrent free where c++11 standard is not guaranteed to be 100% supported. It offers also a flexible way to instantiate the "owned" instance.
Even if the magic static word is enough in c++11 and greater the developer may have the necessity to get much more control over the instance creation.

checking invariants in C++

Are there any established patterns for checking class invariants in C++?
Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.
Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:
template <typename T>
class invariants_checker
{
const T* p;
public:
invariants_checker(const T* p) : p(p)
{
p->check_invariants();
}
~invariants_checker()
{
p->check_invariants();
}
};
void Foo::bar()
{
// class invariants checked by construction of _
invariants_checker<Foo> _(this);
// ... mutate the object
// class invariants checked by destruction of _
}
Question #0: I suppose there is no way to declare an unnamed local variable? :)
We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?
#include <string>
#include <stdexcept>
class Foo
{
std::string str;
std::string::size_type cached_length;
invariants_checker<Foo> _;
public:
Foo(const std::string& str)
: str(str), cached_length(str.length()), _(this) {}
void check_invariants() const
{
if (str.length() != cached_length)
throw std::logic_error("wrong cached length");
}
// ...
};
Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?
Question #2: Do you see any other problems with this approach? Can you improve it?
Question #3: Is this approach new or well-known? Are there better solutions available?
Answer #0: You can have unnamed local variables, but you give up control over the life time of the object - and the whole point of the object is because you have a good idea when it goes out of scope. You can use
void Foo::bar()
{
invariants_checker<Foo>(this); // goes out of scope at the semicolon
new invariants_checker<Foo>(this); // the constructed object is never destructed
// ...
}
but neither is what you want.
Answer #1: No, I believe it's not valid. The object referenced by this is only fully constructed (and thus starts to exist) when the constructor finished. You're playing a dangerous game here.
Answer #2 & #3: This approach is not new, a simple google query for e.g. "check invariants C++ template" will yield a lot of hits on this topic. In particular, this solution can be improved further if you don't mind overloading the -> operator, like this:
template <typename T>
class invariants_checker {
public:
class ProxyObject {
public:
ProxyObject(T* x) : m(x) { m->check_invariants(); }
~ProxyObject() { m->check_invariants(); }
T* operator->() { return m; }
const T* operator->() const { return m; }
private:
T* m;
};
invariants_checker(T* x) : m(x) { }
ProxyObject operator->() { return m; }
const ProxyObject operator->() const { return m; }
private:
T* m;
};
The idea is that for the duration of a member function call, you create an anonymous proxy object which performs the check in its constructor and destructor. You can use the above template like this:
void f() {
Foo f;
invariants_checker<Foo> g( &f );
g->bar(); // this constructs and destructs the ProxyObject, which does the checking
}
Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function
I think this is overkill; I instead check invariants judiciously. The data members of your class are private (right?), so only its member functions can change the data memebers and therefore invalidate invariants. So you can get away with checking an invariant just after a change to a data member that particiaptes in that invariant.
Question #0: I suppose there is no way to declare an unnamed local variable? :)
You can usually whip up something using macros and __LINE__, but if you just pick a strange enough name, it should already do, since you shouldn't have more than one (directly) in the same scope. This
class invariants_checker {};
template<class T>
class invariants_checker_impl : public invariants_checker {
public:
invariants_checker_impl(T* that) : that_(that) {that_->check_invariants();}
~invariants_checker_impl() {that_->check_invariants();}
private:
T* that_;
};
template<class T>
inline invariants_checker_impl<T> get_invariant_checker(T* that)
{return invariants_checker_impl<T>(that);}
#define CHECK_INVARIANTS const invariants_checker&
my_fancy_invariants_checker_object_ = get_invariant_checker(this)
works for me.
Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?
I'm not sure whether it invokes UB technical. In practice it would certainly be safe to do so - where it not for the fact that, in practice, a class member that has to be declared at a specific position in relation to other class members is going to be a problem sooner or later.
Question #2: Do you see any other problems with this approach? Can you improve it?
See #2. Take a moderately sized class, add half a decade of extending and bug-fixing by two dozen developers, and I consider the chances to mess this up at at least once at about 98%.
You can somewhat mitigate this by adding a shouting comment to the data member. Still.
Question #3: Is this approach new or well-known? Are there better solutions available?
I hadn't seen this approach, but given your description of before() and after() I immediately thought of the same solution.
I think Stroustrup had an article many (~15?) years ago, where he described a handle class overloading operator->() to return a proxy. This could then, in its ctor and dtor, perform before- and after-actions while being oblivious to the methods being invoked through it.
Edit: I see that Frerich has added an answer fleshing this out. Of course, unless your class already needs to be used through such a handle, this is a burden onto your class' users. (IOW: It won't work.)
#0: No, but things could be slightly better with a macro (if you're ok with that)
#1: No, but it depends. You cannot do anything that would cause this to be dereferenced in before the body (which yours would, but just before, so it could work). This means that you can store this, but not access fields or virtual functions. Calling check_invariants() is not ok if it's virtual. I think it would work for most implementations, but not guaranteed to work.
#2: I think it will be tedious, and not worth it. This have been my experience with invariant checking. I prefer unit tests.
#3: I've seen it. It seems like the right way to me if you're going to do it.
unit testing is better alternative that leads to smaller code with better performance
I clearly see the issue that your destructor is calling a function that will often throw, that's a no-no in C++ isn't it?