开发者

What happens when i throw an exception in c++ destructor? [duplicate]

开发者 https://www.devze.com 2023-01-10 12:30 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: throwing exceptions out of a destr开发者_Python百科uctor
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

throwing exceptions out of a destr开发者_Python百科uctor

In C++ we should never throw an exception in the destructor . Does this code works as intended ?

struct a 
{ 
    ~a( ) { } 
};
struct b : public a 
{
    ~b( ) 
    { 
        throw 1; 
    }; 
};
bool c( ) 
{ 
    a* d=new b; 
    try 
    { 
        delete d; 
    } 
    catch( int e ) 
    { 
        return e; 
    }
    return false; 
}


Does this code works as intended ?

Did you try running it yourself? Also have a look at this FAQ - according to that, yes, it will work in your simple case, but in general, you shouldn't do it. Again, it depends on how you define "work as intended" - the program will run without errors but you will possibly leak memory because the object wasn't freed.

0

精彩评论

暂无评论...
验证码 换一张
取 消