What if RAII constructor fails due to exception | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

What if RAII constructor fails due to exception

Hi I was doing allocation in construction and deallocation in destructor to achieve RAII like a smart pointer do behind the scene. https://www.sololearn.com/en/compiler-playground/cAIk2bYhv3pC It seems all ok , but a thought came to my mind that what if constructor throws exception post heap allocation? If not catched, destructor will not be called and memory leak happens. If catched, object will not be in properly constructed state and end user might use the ill constructed objects. What is the best scenario here to be implemented? https://code.sololearn.com/cAIk2bYhv3pC/?ref=app

7th Dec 2023, 4:08 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 ответов
+ 1
if the constructor throws an exception after heap allocation, you need to catch the exception and ensure that any allocated resources are properly released. in the code snippet below : https://www.sololearn.com/en/compiler-playground/cE6BQ3kbmwEC https://code.sololearn.com/cE6BQ3kbmwEC/?ref=app when the constructor throws an exception after heap allocation the catch block will be executed. inside the catch block we need to ensure that any allocated resources are properly released ( if it was allocated ) before re-throwing the exception to propagate it to the higher level ( main function ).
7th Dec 2023, 1:12 PM
MO ELomari
MO ELomari - avatar
0
Thanks 😊 MO ELomari
7th Dec 2023, 3:23 PM
Ketan Lalcheta
Ketan Lalcheta - avatar