An exception is passed by value.

When I write my try/catch blocks, I always throw objects by value and exit the link. I also apply the rule that the most derived classes should be first.

Today I tried to catch BY VALUE, breaking this basic rule. The code below runs without any problems and prints "A4" .

Question: What type of CCA argument is passed to the exception handler that runs? The original object that was reset, the CCB is passed by value to the CCA object: this is an example of a memory clipping problem or some distortion, i.e. CCA n't trust the CCA ?

Hello

AFG

  class CCA{ int m_value; public: CCA( int value ) : m_value( value ){} }; class CCB : public CCA{ public: CCB( int value ): CCA( value ){} }; main(){ try{ throw CCB(4); }catch( CCA a ){ std::cout << " A:" << a.value() << std::endl; // this is the catch clause that executes }catch( CCB b ){ std::cout << " B:" << b.value() << std::endl; } } 
+4
source share
2 answers

This is slicing : the inability of the base copy constructor to distinguish an argument of a genuinely of the same type from one of the derived class type:

 struct Base { Base(Base const &); // must accept any derived class }; 
+3
source

The catch block for exclusion is always selected so that it appears in the code. Therefore, if you reorder the exceptions you have programmed, type B:4

The first catch clause was selected in your code, and the copy-constructor for the base class passed an instance of the copy of the original, but it will be a real instance of the base class.

The usual solution is to provide catch blocks in the nearest first order and pass parameters by reference.

+1
source

Source: https://habr.com/ru/post/1384803/


All Articles