catching std::exception by reference?

后端 未结 4 1061
时光取名叫无心
时光取名叫无心 2021-02-01 05:30

I have a silly question. I read this article about std::exception http://www.cplusplus.com/doc/tutorial/exceptions/

On catch (exception& e), it says:

4条回答
  •  梦谈多话
    2021-02-01 06:11

    The reason for using & with exceptions is not so much polymorphism as avoiding slicing. If you were to not use &, C++ would attempt to copy the thrown exception into a newly created std::exception, potentially losing information in the process. Example:

    #include 
    #include 
    
    class my_exception : public std::exception {
      virtual const char *what() const throw() {
        return "Hello, world!";
      }
    };
    
    int main() {
      try {
        throw my_exception();
      } catch (std::exception e) {
        std::cout << e.what() << std::endl;
      }
      return 0;
    }
    

    This will print the default message for std::exception (in my case, St9exception) rather than Hello, world!, because the original exception object was lost by slicing. If we change that to an &:

    #include 
    #include 
    
    class my_exception : public std::exception {
      virtual const char *what() const throw() {
        return "Hello, world!";
      }
    };
    
    int main() {
      try {
        throw my_exception();
      } catch (std::exception &e) {
        std::cout << e.what() << std::endl;
      }
      return 0;
    }
    

    Now we do see Hello, world!.

提交回复
热议问题