禁止实例化为临时对象(C ++) [英] prohibiting instantiation as a temporary object (C++)

查看:201
本文介绍了禁止实例化为临时对象(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在c ++中使用哨兵类,但我似乎有一个精神痛苦,导致重复写错误,如下所示:

I like using sentry classes in c++, but I seem to have a mental affliction that results in repeatedly writing bugs like the following:

{
  MySentryClass(arg);
  // ... other code
}

不用说,失败,因为哨兵在创建之后立即死亡,而不是如所期望的那样在范围的结束处死亡。有没有办法防止MySentryClass被实例化为一个临时的,所以上面的代码无法编译,或至少中止与运行时的错误信息?

Needless to say, this fails because the sentry dies immediately after creation, rather than at the end of the scope, as intended. Is there some way to prevent MySentryClass from being instantiated as a temporary, so that the above code either fails to compile, or at least aborts with an error message at runtime?

推荐答案

我不能想到一个自动的方式来检测你是否犯了这个错误。

I can't think of an automatic way to detect if you make this mistake or not. You could always create a macro that expands to the correct thing and use that to declare the sentry instead if you keep using it wrong.

#define MY_SENTRY_CLASS(_X) MySentryClass _sentry(_X)

,然后使用

MY_SENTRY_CLASS(arg);

或将后贴放在显示器上提醒您。

or put a post-it on your monitor to remind you.

这篇关于禁止实例化为临时对象(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆