以下代码可在WebKit中找到:
RefPtr<Element> element = pendingScript.releaseElementAndClear();
if (ScriptElement* scriptElement = toScriptElement(element.get())) {
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document);
//Do something else...
}
}
NestingLevelIncrementer是一个简单的类,可以增加构造中的计数器并减少它的破坏。您可以查看实施here。
在这个废料中,我认为这类似于直接增加和减少数量。也许唯一的好处是无论如何减少数量,但引入了一个新的类。
使用此模式的任何其他原因?
答案 0 :(得分:2)
无论something else
如何结束,目的都是为了反转增量;当方法返回或抛出异常时,将销毁stack变量。
其他语言的替代方法将使用try...finally
;有关C ++中RAII的最新讨论,请参阅此内容:
Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)