Copy the abandoned object constructor throws - why is the abandoned object still thrown?

Pay attention to the following code:

struct exception_in_copy_constructor { exception_in_copy_constructor() = default; ~exception_in_copy_constructor() = default; exception_in_copy_constructor(const exception_in_copy_constructor& other) { throw std::exception(":-("); } }; 

Now itโ€™s clear that when I throw this object, std :: exception will be thrown.

So let's look at the following code:

 try { exception_in_copy_constructor ecc; throw ecc; } catch(exception_in_copy_constructor& ecc) { printf("IN exception_in_copy_constructor&\r\n"); } catch(std::exception& ex) { printf("IN std::exception&\r\n"); } 

I would expect that before ecc is thrown, std :: exception will be thrown, and because of this, ecc will never be thrown. The above code confirmed that by printing "IN std :: exception &"

BUT remember this code:

 try { exception_in_copy_constructor ecc; throw ecc; } catch(exception_in_copy_constructor& ecc) { printf("IN exception_in_copy_constructor&\r\n"); } 

I would expect nothing to fall into, but, to my surprise, catch(exception_in_copy_constructor& ecc) caught the exception (?!?!)

Can anyone explain what is happening?

I am using VS2015

Thanks!

EDIT: Users wrote that they cannot reproduce, so I write all the code, like on my computer. In addition, I use VS2015, debug, x64 (it also plays in version).

Here is the code:

 int main() { struct exception_in_copy_constructor { exception_in_copy_constructor() = default; ~exception_in_copy_constructor() = default; exception_in_copy_constructor(const exception_in_copy_constructor& other) { throw std::exception(":-("); } }; try { exception_in_copy_constructor ecc; throw ecc; } catch(exception_in_copy_constructor&) { printf("We will never get here!\r\n"); } return 0; } 
+5
source share

Source: https://habr.com/ru/post/1268304/


All Articles