vendredi 11 mai 2018

try and cath in C++ - how many objects are created

Consider the following code:

#include <iostream>
#include <string>
class Box{
    public: 
        std::string show(){
            std::cout<<"Box show executed"<<std::endl;
            return "msg";
        };

        ~Box(){
            std::cout<<"Box destructor is executed"<<std::endl;
        };
};

int main(){

    try{
        Box obj;
        std::cout<<"Coming here"<<std::endl;
        throw obj;
    }
    catch(Box msg){
        std::cout<<"I have caught the exception: \n"<<msg.show()<<std::endl;
    }

}

In GCC compiler the output is:

Coming here
Box destructor is executed
Box show executed
I have caught the exception:
msg
Box destructor is executed
Box destructor is executed

My confusions are:

  1. The statement prints are very confusing, why is the "Box show executed" printing before the "I have caught the exception" line?

  2. There are three destructors called, How is this possible when only two objects are created, one the Box object in the try and the temp object in the try which is passed to the catch block?

Aucun commentaire:

Enregistrer un commentaire