I want to use a stateless scope guard
struct ScopeGuard {
ScopeGuard();
~ScopeGuard();
};
void f();
int test() {
ScopeGuard scopeguard1;
ScopeGuard scopeguard2;
// doesn't work:
// [[no_unique_address]] ScopeGuard scopeguard3;
f();
}
The scope guard itself has no state, I am only interested in the side effects of the constructor/destructor.
I want test
to have a stack size of 0.
But scopeguard1
and scopeguard2
take 8 bytes of stack space each. This is because the this
pointer needs to be unique for each instance of ScopeGuard
, even if it is stateless.
Usually, I would want to use [[no_unique_address]]
in this situation. But it seems [[no_unique_address]]
only works for member variables but not for local variables inside functions.
Is there some other way to achieve this?
Why is [[no_unique_address]]
only supported for member variables? Was this an oversight in C++20? Was it intentional? Would there be any issues with allowing this attribute also for local variables?