2

あなたは試してみることができます。以下のプログラムはコンパイルされ、スムーズに実行されます。コンストラクター内の variable のアドレスは、catch ブロック内の一時変数であるのアドレスとexは異なります。しかし、B 行の の値が参照によって に渡されeていることに気付くかもしれません。誰が何が起こっているのか説明できますか?exe

#include<cstring>
#include<iostream>


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<<"destructor get called."<<endl;}
        friend std::ostream& operator<<(std::ostream& os,const ThrowException&TE);
};

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

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

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

}

私が尋ねたいもう 1 つの問題は、ThrowException オブジェクトのデストラクタがいつ呼び出されるかということです。

4

1 に答える 1

7

式はthrow、ローカルスコープを離れる前に、スローされたオブジェクトを安全な場所にコピーします。言語は、それがどこに保存されているかを正確に示していません。これは何らかの形で機能する必要があるということだけです(詳細は実装に任されています)。

于 2012-05-01T08:44:33.660 に答える