@Sid, am I right to assume that the problem with statics only occurs with the use of shared libraries, but not with the use of static libraries?
Yes.
Also, I have no clue what your second snippet does.
It provides a way to execute some code at startup or exit. The macros wrap a static object that is instantiated at startup (or when the library is loaded), and which is destroyed at the end, and depending on which macro is used, it calls a callback in either the constructor or destructor. It exploits the automatic object lifetime in C++.
Similar, a scope guard, which can be used for automatic clean up (more code snippet):
namespace RN
{
class ScopeGuard
{
public:
template<typename F>
explicit ScopeGuard(F &&rollback) :
_committed(false),
_rollback(std::move(rollback))
{}
ScopeGuard(ScopeGuard &&other) :
_committed(other._committed),
_rollback(std::move(other._rollback))
{}
ScopeGuard &operator=(ScopeGuard &&other)
{
_rollback = std::move(other._rollback);
_committed = other._committed;
return *this;
}
~ScopeGuard()
{
if(!_committed)
_rollback();
}
void Commit()
{
_committed = true;
}
private:
bool _committed;
Function _rollback;
};
}
Example usage:
void foo()
{
FILE *file = fopen(...);
RN::ScopeGuard guard([&]() {
fclose(file); // Close the file descriptor
});
bar(file); // In this case, bar can throw an exception.
// Either way, exception or normal exit, once the scope guard goes out of scope, the file is closed.
}
PS: Don't use "FILE" in C++