Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

failed constructor and failed destructor in C++

I have one question about failed constructor and failed destructor in C++.

I noticed that when the constructor failed, an exception will be thrown. But there is no exception thrown in destructor.

My question is

1) If constructor failed, what exception will be thrown? bad_alloc? or anything else related? Under what situation, a constructor would fail? What about the successfully constructed part?

2) Under what situation, a destructor would fail? If no exception is thrown, what would happen to the destructor? How does the compiler deal with it? What's the return value to the function it is called?

Thanks!

Any comments are strongly appreciated!

like image 792
skydoor Avatar asked Dec 12 '22 23:12

skydoor


1 Answers

  1. If a constructor fails, an exception is thrown only if the constructor is implemented so that it throws an exception. (You might need to differentiate between memory allocation and construction. Allocating memory using new might fail throwing a std::bad_alloc exception.)

  2. There is no case where a constructor, in general, fails. It fails only if it is written so that it might fail. If so, how it fails depends on how it is written. In general, destructors should be written so they don't fail, as it is not safe to throw exceptions from destructors. (That's because they might be called during stack unwinding.)

Note that "failing" as used in your question generally refers to runtime failures. So the compiler has nothing to do with it. Also, neither constructors nor destructors return anything.

like image 183
sbi Avatar answered Dec 15 '22 12:12

sbi