宏很好.模板很好.几乎无论它的工作原理都很好.
这个例子是OpenGL; 但该技术是C++特有的,并且不依赖于OpenGL的知识.
精确问题:
我想要一个表达式E; 我不需要指定唯一名称; 这样,在定义E的地方调用构造函数,并在块E的末尾调用析构函数.
例如,考虑:
class GlTranslate {
GLTranslate(float x, float y, float z); {
glPushMatrix();
glTranslatef(x, y, z);
}
~GlTranslate() { glPopMatrix(); }
};
Run Code Online (Sandbox Code Playgroud)
手动解决方案
{
GlTranslate foo(1.0, 0.0, 0.0); // I had to give it a name
.....
} // auto popmatrix
Run Code Online (Sandbox Code Playgroud)
现在,我不仅有glTranslate,还有很多其他的PushAttrib/PopAttrib调用.我宁愿不必为每个var提出一个唯一的名称.是否存在涉及宏模板的一些技巧......或者其他会自动创建变量的变量,在定义点调用构造函数; 和块结束时调用的析构函数?
谢谢!
我正在尝试编写一个基于Alexandrescu概念但使用c ++ 11习语的简单ScopeGuard.
namespace RAII
{
template< typename Lambda >
class ScopeGuard
{
mutable bool committed;
Lambda rollbackLambda;
public:
ScopeGuard( const Lambda& _l) : committed(false) , rollbackLambda(_l) {}
template< typename AdquireLambda >
ScopeGuard( const AdquireLambda& _al , const Lambda& _l) : committed(false) , rollbackLambda(_l)
{
_al();
}
~ScopeGuard()
{
if (!committed)
rollbackLambda();
}
inline void commit() const { committed = true; }
};
template< typename aLambda , typename rLambda>
const ScopeGuard< rLambda >& makeScopeGuard( const aLambda& …Run Code Online (Sandbox Code Playgroud) 我想finally在我的C++程序中实现一个块,如果不是原生设施,那么该语言肯定有工具可以实现.我想知道最好的方法是什么?
我有一个代码,如果之前在代码中有错误,那么这些代码必须不能执行.我实际上使用一个名为bool的bool变量EndProg,如果设置为true,将指示程序避免执行某些代码部分.
我的问题是我不想使用这种方法而我更愿意使用goto它,因为它会使程序跳转到清理部分并避免EndProg多次检查值.
另一个问题是我在StackOverflow和其他网站上的许多页面上阅读过使用goto被认为是一种不好的做法,并且它可能使代码更难以阅读或创建错误.
我的代码很简单,我只需要使用一个标签,所以我怀疑这会产生问题; 但是我想知道是否有其他方法可以做我想要的而不创建执行清理任务或使用的函数return(因为,例如,我需要多次编写清理代码)而且我也不想在多个地方编写相同的大清理代码,然后使用return或执行其他操作.
我不想增加代码行数,也不想使用return或使用很多if也不检查状态变量的值.你会推荐什么 ?
这是一段代码:
bool EndProg=false;
/*
Lot of code that can set EndProg to true
*/
ClassType ClassName;
if(!EndProg && LoadConf(&ConfFilePath,&ClassName)==0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath!=0)strcpy(ClassName.FilePath,"file.ext");
else EndProg=true;
}
if(!EndProg && mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We …Run Code Online (Sandbox Code Playgroud)