Skip to content

Instantly share code, notes, and snippets.

@incrediblejr
Created August 15, 2019 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save incrediblejr/b70415d6c0c7bcca8c724ba58ff3e376 to your computer and use it in GitHub Desktop.
Save incrediblejr/b70415d6c0c7bcca8c724ba58ff3e376 to your computer and use it in GitHub Desktop.
optional instance created by placement-new with stack-memory
/*
* optional instance created by placement-new with stack-memory
*
* ex.
* struct ThreadContextScope {
* ThreadContextScope() { // setup thread-context }
* ~ThreadContextScope() { // teardown thread-context }
* };
*
* void some_function(void) {
* OPTIONAL_INSTANCE(ThreadContextScope, HasThreadContext() == false);
* ...
*/
#include <new> /* 'operator new' : function does not take X arguments */
#define CONCATENATE_DIRECT(s1, s2) s1##s2
#define CONCATENATE(s1, s2) CONCATENATE_DIRECT(s1, s2)
#define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __LINE__)
#define ALIGN(DECL, ALIGNMENT) __declspec(align(ALIGNMENT)) DECL
#define ALIGN_OF(...) __alignof(__VA_ARGS__)
#define OPTIONAL_INSTANCE(klass, condition, ...) \
ALIGN(char ANONYMOUS_VARIABLE(STACKMEMORY_OPTIONAL_INSTANCE)[sizeof(klass)], ALIGN_OF(klass)); \
CallDestructor<klass> ANONYMOUS_VARIABLE(on_exit_scope)((condition) ? (new (ANONYMOUS_VARIABLE(STACKMEMORY_OPTIONAL_INSTANCE)) klass(##__VA_ARGS__)) : 0)
template <typename T>
struct CallDestructor {
CallDestructor(T *ptr) : p(ptr) {}
~CallDestructor() {
if (p)
p->~T();
}
T *p;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment