3 ms·
> IMO constructors should be setting sane defaults and nothing more. If you need to do work that could fail put that into an "init()" function with a return typ
by lmm 11y ago
> IMO constructors should be setting sane defaults and nothing more. If you need to do work that could fail put that into an "init()" function with a return type that can signal an error.
That allows you to construct the object in an invalid state. The whole point of RAII is to avoid that. The acronym literally means not having a separate init() function.
- vvanders 11y agoSorry, I should have clarified that the init function is usually static so you can invoke with it returning an object + possible error code if you never want an object in an invalid state. FWIW some quick googling shows that having a constructor acquire a resource is not a requirement(https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Resource_Acquisition_Is_Initialization#Solution_and_Sample_Code https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Resource_A...). The important part about RAII is that the automatic releasing of resources when out of scope(through a no-throw destructor).
- Manishearth 11y agoYou can solve this problem the Rust way too: don't use a constructor. Create a static `new` method that returns the object to you, with optional error flags. This is still RAII, you're just not using a constructor to acquire. Rust doesn't have constructors and is still RAII.