TITLE: catch by reference or by value (followon) [ This is a previous tip with Kanze's comments added. -adc ] (Newsgroups: comp.lang.c++.moderated, 17 Sep 98) KASPERSKI: "Marcin Kasperski" > > I get used to: > > > > catch (ExceptionClass exc) { > > .... > > } > > > > but recently I've seen somewhere > > > > catch (ExceptionClass& exc) { > > } > > > > I can also imagine catching const &. > > > > Could anyone compare those methods (esp. their efficiency)? > > > > PS. I know people, who decided to throw and catch pointers. What about this > > method? HOPPS: khopps@Adobe.COM (Kevin J. Hopps) > The issues are much like those involved in setting > the types for function parameters, with one important > difference noted below. > > Objects that are thrown as exceptions will be copied > to some place that is implementation-specific. It is > perfectly safe to throw an object that lives on the > stack because it will be copied. > > Catching by value means that the object will be copied > again to the local catch block. Catching by reference > will require one less copy. > > As for the difference between catching by reference vs. > catching by const-reference, obviously you cannot modify > the caught object if the const-reference is used. It > shouldn't matter outside the scope of the handler, unless > the object is rethrown. KANZE: jkanze@otelo.ibmmail.com It does matter, since you may be catching a base class of the thrown object. The second copy will slice; with catch by value, the results will always be of the exact same type that you declare in the catch. With catch by reference, on the other hand, the results will be of that type, or an object derived from that type. HOPPS: > I am not sure what the standard requires when rethrowing > an object caught by reference or const-reference -- will > it make another copy or reuse the existing copy? KANZE: It is required to reuse the existing copy. This is important, since a normal throw will only use the static type of the object thrown. If the rethrow made a copy, once again, it might slice, and thus change the type of the exception. (Not to mention the problem of rethrowing in a catch( ... ) block.)