Re:My favourite C++ footgun
by fpoling on Wednesday June 23, 2021 @04:39AM
(#27602236)
You can also use out parameters to tell about errors.
[ Parent
| on HN ]
Re:My favourite C++ footgun
by johannes1234321 on Wednesday June 23, 2021 @02:19PM
(#27608048)
When doing that the better approach is to use a factory function wrapping this.
However mind that if you don't throw from C++'s perspective the object is fully created, so that the destructor will run.
If you throw an exception from the contractor, the object won't be fully created.
In practice I have not found that running destructor is problematic. In many cases the destructor is the default one that just destructs the fields. When the destructor should be non-default the constructor can leave the object in the move out state either explicitly or via hacks like using T tmp(std::move((*this)) on the error return in the constructor.