简单的说,PopAndDestroy(p)等价于Pop(p); delete p;
关于清理栈的使用:
class CleanupStack
{
public:
IMPORT_C static void PushL(TAny* aPtr);
IMPORT_C static void PushL(CBase* aPtr);
IMPORT_C static void PushL(TCleanupItem anItem);
IMPORT_C static void Pop();
IMPORT_C static void Pop(TInt aCount);
IMPORT_C static void PopAndDestroy();
IMPORT_C static void PopAndDestroy(TInt aCount);
IMPORT_C static void Check(TAny* aExpectedItem);
inline static void Pop(TAny* aExpectedItem);
inline static void Pop(TInt aCount, TAny* aLastExpectedItem);
inline static void PopAndDestroy(TAny* aExpectedItem);
inline static void PopAndDestroy(TInt aCount, TAny* aLastExpectedItem);
};
在调用可能发生异常退出的代码之前,非异常退出安全的对象应该被置于清除栈上,例如:
void SafeFunctionL()
{
CClanger* clanger = new (ELeave) CClanger;
// Push onto the cleanup stack before calling a leaving function
CleanupStack::PushL(clanger);
clanger->InitializeL();
clanger->DoSomethingElseL()
// Pop from cleanup stack
CleanupStack::Pop(clanger);
delete clanger;
}
对象必须以严格的顺序压入和弹出清除栈:一组Pop()操作必须与PushL()调用顺序相反。可能会发生调用Pop()或PopAndDestroy()弹出对象而没有命名这些对象的情况,但最好还是要对弹出对象进行命名。这样可以避免任何潜在的清除栈“不平衡”的错误。
void ContrivedExampleL()
{
// Note that each object is pushed onto the cleanup stack
// immediately it is allocated, in case the succeeding allocation
// leaves.
CSiamese* sealPoint = NewL(ESeal);
CleanupStack::PushL(sealPoint);
CSiamese* chocolatePoint = NewL(EChocolate);
CleanupStack::PushL(chocolatePoint);
CSiamese* violetPoint = NewL(EViolet);
CleanupStack::PushL(violetPoint);
CSiamese* bluePoint = NewL(EBlue);
CleanupStack::PushL(bluePoint);
sealPoint->CatchMouseL();
// Other leaving function calls, some of which use the cleanup stack
...
// Various ways to remove the objects from the stack and delete them:
// (1) All with one anonymous call - OK, but potentially risky
// CleanupStack::PopAndDestroy(4);
// (2) All, naming the last object - Better
// CleanupStack::PopAndDestroy(4, sealPoint);
// (3) Each object individually to verify the code logic
// Note the reverse order of Pop() to PushL()
// This is quite long-winded and probably unnecessary in this
// example
CleanupStack::PopAndDestroy(bluePoint);
CleanupStack::PopAndDestroy(violetPoint);
CleanupStack::PopAndDestroy(chocolatePoint);
CleanupStack::PopAndDestroy(sealPoint);
}
如果有对象被压入清除栈,并直至函数返回时还保留在清除栈上,则该函数应该以"C"作为后缀。这就告诉函数调用者,如果函数返回正常,清除栈上仍然有多余的对象。这种方法通常被CBase派生类所使用,这些类通常定义有静态函数用来实例化对象并将对象留着清除栈上。C后缀函数向函数调用者传达这样的信息:不需要将函数中分配的对象再压入清除栈中。
本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/hzb1983/archive/2009/06/21/4287176.aspx