More effective C + +: Catching exceptions by reference

Source: Internet
Author: User

When you write a catch clause, you must determine how the exception is passed into the catch clause. You can have three choices: as you pass arguments to a function, through a pointer (by pointer), through a value (by value) or by reference (by reference).

We first discuss catching an exception by means of a pointer (catch by pointer). Passing an exception to a catch clause from the throw is a slow process, and in theory the implementation of this method is the most efficient for the process. Because when exception information is passed, only methods that throw an exception through the pointer can be used to not copy the object, for example:

class exception { ... }; // 来自标准C++库(STL)
 // 中的异常类层次
 void someFunction()
 {
  static exception ex; // 异常对象
  ...
  throw &ex; // 抛出一个指针,指向ex
  ...
 }
 void doSomething()
 {
  try {
   someFunction(); // 抛出一个 exception*
  }
  catch (exception *ex) { // 捕获 exception*;
   ... // 没有对象被拷贝
  }
 }

It looks good, but that's not the case. In order for the program to work properly, the programmer must define the exception object to ensure that the object continues to survive when the program control leaves the function that throws the pointer. Both global and static objects can do this, but it is easy for programmers to forget this constraint. If that's the case, they'll write code like this:

void someFunction()
{
 exception ex; // 局部异常对象;
 // 当退出函数的生存空间时
 // 这个对象将被释放。
 ...
 throw &ex; // 抛出一个指针,指向
 ... // 已被释放的对象
}

This is simply awful, because the object that handles this exception's catch clause receives a pointer that no longer exists.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.