EDIT:
Although it's for C, I think the accepted answer to Possible to define a function-like macro with a variable body? can be of use here.
It's possible to create macro in such fashion by utilizing for
loop. Example:
#include <iostream>
struct Foo {
int bar;
Foo(int bar) : bar(bar) { std::cout << 1 << std::endl; }
~Foo() { std::cout << 3 << std::endl; }
};
#define TEST(var) \
for (bool flag = true; flag; ) \
for (Foo foo(var); flag; flag = false)
int main()
{
int x = 2;
TEST(x) {
std::cout << foo.bar << std::endl;
}
// std::cout << foo.bar << std::endl; // ERROR: ‘foo’ was not declared in this scope
std::cout << 4 << std::endl;
return 0;
}
Both loops will execute if flag
is true. First loop initializes flag
to this value. Second loop creates object foo
. After expansion the "body" of TEST
becomes the body of second loop. After executing the code (everything declared inside body is should be properly destroyed by now), the second loop sets flag
to false and therefore ends. First loops also ends and destroys the flag
.
The problem is, you want to use it in multithreaded program. This approach will certainly result in data races.
Personally, I wouldn't play around with such macros, but just simply do something in such manner:
using mutex_lock_guard = std::lock_guard<std::mutex>;
std::mutex;
void func(int x)
{
// init...
{
mutex_lock_guard lock(mutex);
// body..
}
}
Or else still with macros:
#define LOCK_GUARD(var) std::lock_guard<std::mutex> lock(var)
std::mutex;
void func(int x)
{
// init...
{
LOCK_GUARD(mutex);
// body..
}
}