使用宏创建自定义块类型

Create a custom block type using macros

在 avr-gcc 中你可以这样:

ATOMIC_CODE{
   cout << "Here I can do stuff that is very time sensitive\n";
}

不幸的是,这是一个使用特殊 gcc 属性 的#define,我想避免这种情况。

所以解决方法是:

void enableInterrupts(){ std::cout << "Interupts Enabled\n"; }
void disableInterrupts() { std::cout << "Interupts Disabled\n"; }
class Scoped{
    void (*cleanup)();
    bool incremented;
    public:
        Scoped(void (*clean)(),void (*before)()) : cleanup(clean),incremented(false){
            before();
        }
        ~Scoped(){
            cleanup();
        }
        void operator ++(){
            incremented = true;
        }
        bool operator!(){
            return !incremented;
        }

};
#define ATOMIC for (Scoped x(&enableInterrupts,&disableInterrupts); !x; ++x)

//Later in main.cpp
ATOMIC{
    /*do stuff*/
    std::cout << "This is atomic code\n";
}

唯一的问题是它依赖于立即调用析构函数(我不确定这是一种可靠的方法)。

那么是否保证析构函数会立即被调用,或者编译器是否可以在需要时析构对象?

是的,保证立即调用析构函数。

https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

您正在考虑执行惰性标记和清扫垃圾收集的语言。 (好吧,也许你不是)