Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with failed constructor when throwing exceptions is not allowed

I was looking at the Google C++ Style Guide and they have decided not to use exceptions in C++ code, relying on return values instead.

My question is: How do you handle failure in constructors in this case, since you cannot return a value in those.

Thanks!

like image 748
recipriversexclusion Avatar asked Nov 27 '25 16:11

recipriversexclusion


1 Answers

My first instinct would be to take the failure point out of the constructor, and create an initialisation method.

This way you can create your object without fear of failure, then call the init() function. That function can return something like an int for success/failure, for example -1 if the failure occurs.

Yes this is an extra step, but it does get you around not being able to fail a constructor

like image 92
Dunderklumpen Avatar answered Nov 29 '25 05:11

Dunderklumpen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!