使用宏创建自定义块类型(Create a custom block type using macros)

编程入门 行业动态 更新时间:2024-10-28 15:30:16
使用宏创建自定义块类型(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"; }

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

那么是否可以保证析构函数会立即被调用,或者编译器可以在它感觉到的时候破坏对象?

In avr-gcc you can something like this:

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

Unfortunately this is a #define which uses a special gcc atribute, which I would like to avoid.

So a workaround is this:

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"; }

The only problem is that it relys on the destructor getting called immediately (which I am not sure is a reliable method).

So is it guaranteed that the destructor will get called immediately or can the compiler destruct the object whenever it feels like it?

最满意答案

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

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

你正在考虑做懒惰标记和扫描垃圾收集的语言。 (好吧,也许你不是)

Yes, it is guaranteed that the destructor will be called immediately.

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

You're thinking about languages that do lazy mark and sweep garbage collection. (ok, maybe you're not)

更多推荐

本文发布于:2023-07-28 22:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1309797.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   类型   Create   custom   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!