使用宏创建自定义块类型

Create a custom block type using macros

本文关键字:类型 自定义 创建      更新时间:2023-10-16

在avr gcc中,您可以执行以下操作:

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

不幸的是,这是一个#define,它使用了一个特殊的gccatribute,我想避免它。

因此,一个变通方法是:

void enableInterrupts(){ std::cout << "Interupts Enabledn"; }
void disableInterrupts() { std::cout << "Interupts Disabledn"; }
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 coden";
}

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

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

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

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

您正在考虑的语言可以进行懒惰标记和清除垃圾收集。(好吧,也许你不是)