一、为什么不和C++统一:
因为Symbian 在错误处理在C++有exception之前有就了,而且后来c++的try/catch 机制会使编译后的文件变大和效率问题。最后Symbian 还是使用自己的方式。
二、离开函数 (Leave Function)
所有在函数体内会调用User::Leave 系统函数退出的都应该将函数名设置为 L 结束;
Example:
三、new (ELeave) ...
Symbian 重载了 operator new ,并增加了 ELeave 参数;
调用:
CClanger* clanger = new (ELeave) CClanger();
则如果内存不足,会自动调用 Leave 函数;
而如果直接调用
CClanger* clanger = new CClanger();
则要要后面的使用进行判断:
if (clanger)
{
//.....
}
四、构造和析构
在构造和析构中一定不能调用 Leave 相关函数。
五、Leave 函数的使用
//安全使用
void FunctionMayLeaveL()
{
// Allocates ironChicken on the heap
CTestClass* ironChicken = CTestClass::NewL();
// If NewL() didnЎЇt leave, ironChicken was allocated successfully
ironChicken->FunctionDoesNotLeave();
delete ironChicken;
}
//不安全使用
void UnsafeFunctionL()
{
// Allocates test on the heap
CTestClass* test = CTestClass::NewL();
test->FunctionMayLeaveL(); // Unsafe ЁC a potential memory leak!
delete test;
}
//安全使用,使用成员变量,最后一起清除
void CTestClass::SafeFunctionL()
{
iMember = CClangerClass::NewL(); // Allocates a heap member
FunctionMayLeaveL(); // Safe
}
//安全使用,因为不用担心 T 类型实例数据不被析构
class TMyClass
{
public:
TMyClass(TInt aValue);
private:
TInt iValue;
};
//推荐的安全做法,增加到了 ClearnUpStack 的堆栈中,个人想肯定会在TRAP和TRAPD中进行处理;
//但是这种情况,如果是多线程的要如何处理?不能保证,弹出的就是刚才Push的.
void AnotherFunctionL()
{
TMyClass* localObject = new (ELeave) TMyClass();
// Make localObject leave-safe using the cleanup stack
CleanupStack::PushL(localObject);
AnotherPotentialLeaverL(localObject);
CleanupStack::PopAndDestroy(localObject);
}
六、TRAP 和 TRAPD,
TRAP和TRAPD应该尽量少用,因为这种错误系统处理是要发很大代价的,但系统最后要有一个地方TRAP错误。
调用这二个捕捉函数代
TRAPD(result, SomeFunctions()) 和 TRAP(result, SomeFunction())的区别是:
TRAPD 默认定义了一个 result 的TInt 变量;
七、LeaveScan 工具
LeaveScan will highlight functions which may leave but are incorrectly
named without a suffixed ”L”. The potential to leave occurs
when a function:
• calls other functions which themselves leave (and thus have
function names ending in L) but does not surround the function
call with a TRAP harness
• calls a system function which initiates a leave, such as
User::LeaveIfError() or User::Leave()
• allocates an object on the heap using the Symbian OS overload
of operator new.