Symbian 学习笔记(二、异常处理)

本文介绍了Symbian OS中独特的错误处理机制,包括为何不采用C++标准异常处理、Leave函数的使用规范、资源管理技巧及TRAP/TRAPD的适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、为什么不和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 的堆栈中,个人想肯定会在TRAPTRAPD中进行处理;

//但是这种情况,如果是多线程的要如何处理?不能保证,弹出的就是刚才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,

     TRAPTRAPD应该尽量少用,因为这种错误系统处理是要发很大代价的,但系统最后要有一个地方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.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值