Throwing non-const temporaries by reference

后端 未结 1 1415
余生分开走
余生分开走 2021-01-15 09:37

Is there any problem with throwing an object constructed on the stack in a try-block by non-const reference, catching it and modifying it, then throwing it by reference to a

相关标签:
1条回答
  • 2021-01-15 10:04

    There's no such thing as "throwing by reference". It is simply impossible. There's no syntax for that. Every time you try to "throw a reference", a copy of the referenced object is actually thrown. Needless to say, there are no attempts to throw by reference in your code.

    It is possible to catch a previously thrown exception by reference (even by a non-const one) and modify the temporary exception object through it. It will work. In fact, you can re-throw the now-modified existing exception object instead of creating a new one. I.e. you can just do

    throw;
    

    instead of

    throw e;
    

    in your catch clauses and still get the correctly behaving code, i.e. the original object (with modifications) will continue its flight throgh the handler hierarchy.

    However, your code is ill-formed at the

    e.app("1"); 
    

    call (and other calls to app) since the parameter is non-const reference. Change the app declaration to either

    void app(const string& t) { where += t; }  // <- either this
    void app(string t) { where += t; }         // <- or this
    

    for it to compile.

    Otherwise, you code should work fine. You are not supposed to get any garbage from get(). If you do, it must be either a problem with your compiler or with your code that you don't show.

    0 讨论(0)
提交回复
热议问题