How can a catch block catch a reference to a temporary variable in an other scope?
<p>You could have a try. The program below compiles and runs smoothly. The address of variable <code>ex</code> in the constructor is different from that of <code>e</code>, a temporary variable in the catch block. Yet you may notice that the value of <code>ex</code> in line B is passed to <code>e</code> by reference. Could anyone explain what's going on?</p>

<pre><code>#include&lt;cstring&gt;
#include&lt;iostream&gt;


using std::string;
using std::endl;
using std::cout;

class ThrowException;
ThrowException* TE_ptr;

class ThrowException{

    private:
        string msg;
        int b;
    public:
        ThrowException(string m="Unknown exception",int factor=0) throw(string,const char*);
        ~ThrowException(){        cout&lt;&lt;"destructor get called."&lt;&lt;endl;}
        friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os,const ThrowException&amp;TE);
};

ThrowException::ThrowException(string m, int f) throw(string,const char*):msg(m),b(f){
    cout&lt;&lt;"msg="&lt;&lt;msg&lt;&lt;'\n'&lt;&lt;"b="&lt;&lt;b&lt;&lt;endl;
    TE_ptr=this;
    if(b==1){
        string ex("b=1 not allowed.");
        cout&lt;&lt;"The address of e in constructor is "&lt;&lt;&amp;ex&lt;&lt;endl;      //A
        throw ex;
    }
}

std::ostream&amp;operator&lt;&lt;(std::ostream&amp;os, const ThrowException &amp;TE){
    os&lt;&lt;TE.msg&lt;&lt;'\n'&lt;&lt;TE.b&lt;&lt;endl;
}
int main(){

    try{
        ThrowException a("There's nothing wrong.", 1);
    }catch(string &amp;e){             //B
        cout&lt;&lt;"The address of e in first catch block is "&lt;&lt;&amp;e&lt;&lt;endl;        //C
        cout&lt;&lt;"The content resided in the momery block pointed to by TE_ptr is "&lt;&lt;*TE_ptr&lt;&lt;endl;
    }

}
</code></pre>

<p>Another problem I would like to ask is when will the destructor of ThrowException object a be called?</p>
