4 ms·
I'm no C++ expert. But Wouldn't a private constructor and a static method that returns nil if input is bad fix this problem? Joshua Kerievsky talks a bout this
by cenny 5y ago
I'm no C++ expert. But Wouldn't a private constructor and a static method that returns nil if input is bad fix this problem?
Joshua Kerievsky talks a bout this problem in his book [Refactoring to patterns](https://www.programmingbooks.dev/#refactoring-to-patterns https://www.programmingbooks.dev/#refactoring-to-patterns), specifically the refactoring "Replace Constructors with Creation Methods"
That is maybe beside the point of the articles argument he is making about C++ being bloated and hard to use and read ¯\_(ツ)_/¯
- brigade 5y agoThen you can't allocate the object in-place (e.g. on the stack), and also you have to ban copy assignment/construction. Probably a more common solution is like what STL's own fstream does - don't throw an exception on construction, and have a "not valid" state.
- atq2119 5y agoSorry to say it, but your C++ knowledge seems outdated. What the gp comment explained is perfectly viable due to (Named) Return Value Optimization is for. Compilers have been doing that for a while and it's mandatory since C++17. Yes, C++ has started changing a lot about a decade ago, and despite what the naysayers claim, most of the changes (like this one) are for the better.
- brigade 5y agoHow exactly do you return a null object by value? I know about RVO, but that's irrelevant here because a factory function returning an object by value does nothing to avoid needing to throw exceptions if construction fails.