如果是局部指针的话,需要这样(否则heap内的内存无法回收):
void SafeFunctionL() { CAnotherClass* theObject = new (ELeave) CAnotherClass(); // Push to the cleanup stack before calling // any methods that may leave. CleanupStack::PushL(theObject); // If leave happens here, theObject will still be // deleted. theObject ->InitializeL(); // Pop the object from the cleanup stack. CleanupStack::Pop(theObject); // And finally delete the object. delete theObject; // Alternatively, the last 2 lines of code can // be expressed in one line, as follows: // CleanupStack::PopAndDestroy(theObject); }
而如果是类的成员变量,则可以放心大胆地如下:
void CTestClass::SafeFunctionL() { // Heap allocation of a member variable iTheObject = new(ELeave) CAnotherClass(); iTheObject ->InitializeL(); // Safe for iTheObject }