Originally Posted By: the_clown
@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.

Originally Posted By: the_clown
Also, I have no clue what your second snippet does. tongue

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):
Code:
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:
Code:
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++ tongue


Shitlord by trade and passion. Graphics programmer at Laminar Research.
I write blog posts at feresignum.com