而不是每次都做以下
start();
// some code here
stop();
Run Code Online (Sandbox Code Playgroud)
我想定义某种宏,它可以写成:
startstop()
{
//code here
}
Run Code Online (Sandbox Code Playgroud)
在C++中有可能吗?
Gre*_*ill 41
你可以使用一个小的C++助手类做一些非常接近的事情.
class StartStopper {
public:
StartStopper() { start(); }
~StartStopper() { stop(); }
};
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中:
{
StartStopper ss;
// code here
}
Run Code Online (Sandbox Code Playgroud)
当执行进入块并构造ss变量时,start()将调用该函数.当执行离开块时,StartStopper将自动调用析构函数,然后调用stop().
ava*_*kar 14
在C++中执行此操作的惯用方法称为资源获取初始化,或称为RAII.除了提供您想要的内容之外,它还具有异常安全的附加好处:stop即使您的代码抛出异常,也会调用该函数.
定义一个保护结构:
struct startstop_guard
{
startstop_guard()
{
start();
}
~startstop_guard()
{
stop();
}
};
Run Code Online (Sandbox Code Playgroud)
然后以这种方式重写代码:
{
startstop_guard g;
// your code
}
Run Code Online (Sandbox Code Playgroud)
防护的析构函数(以及stop函数)将在封闭块的末尾自动调用.
小智 6
其他答案已经很好地解决了问题的RAII方面,所以我将解决它的语法方面.
#define startstop for(Starter s; s.loop; s.loop = false)
struct Starter {
bool loop;
Starter() { start(); loop = true; }
~Starter() { stop(); }
};
Run Code Online (Sandbox Code Playgroud)
使用如下:
startstop {
// some code
}
Run Code Online (Sandbox Code Playgroud)
应该是不言自明的.