Created
August 15, 2019 11:18
-
-
Save incrediblejr/b70415d6c0c7bcca8c724ba58ff3e376 to your computer and use it in GitHub Desktop.
optional instance created by placement-new with stack-memory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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