哪个是对的? catch(_com_error e)或catch(_com_error& e)? [英] Which is correct? catch (_com_error e) or catch (_com_error& e)?

查看:900
本文介绍了哪个是对的? catch(_com_error e)或catch(_com_error& e)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用哪一个?

  catch(_com_error e)
/ pre>

  catch(_com_error& e)


解决方案

这是我试图引用Sutter的尝试



按值引用,按引用捕获


正确地学习 catch :通过值(非指针)和
抛出异常通过引用捕获它们(通常为 const )。这是组合
,最好与异常语义。当重新抛出相同的
异常时,更喜欢 throw; throw e;


这是完整的项目73.按值引用,按引用捕获。






通过值捕获异常是它隐式地生成异常的副本。如果异常是一个子类,那么有关它的信息将丢失。

  try {throw MyException(error)} 
catch(Exception e){
/ *隐含:异常e(MyException(error))* /
/ * e是异常的实例,但不是MyException * /
}
pre>

通过引用捕获可避免不复制异常而导致的此问题。

  try {throw MyException(error)} 
catch(Exception& e){
/ * Implies:Exception& e = MyException * /
/ * e是MyException的实例* /
}


Which one should I use?

catch (_com_error e)  

or

catch (_com_error& e)

解决方案

The second. Here is my attempt at quoting Sutter

"Throw by value, catch by reference"

Learn to catch properly: Throw exceptions by value (not pointer) and catch them by reference (usually to const). This is the combination that meshes best with exception semantics. When rethrowing the same exception, prefer just throw; to throw e;.

Here's the full Item 73. Throw by value, catch by reference.


The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost.

try { throw MyException ("error") } 
catch (Exception e) {
    /* Implies: Exception e (MyException ("error")) */
    /* e is an instance of Exception, but not MyException */
}

Catching by reference avoids this issue by not copying the exception.

try { throw MyException ("error") } 
catch (Exception& e) {
    /* Implies: Exception &e = MyException ("error"); */
    /* e is an instance of MyException */
}

这篇关于哪个是对的? catch(_com_error e)或catch(_com_error& e)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆