3 ms·
Another solution if you can't use exceptions is to have something like a valid() method that the user can call to verify that the object has been correctly init
by spacechild1 5y ago
Another solution if you can't use exceptions is to have something like a valid() method that the user can call to verify that the object has been correctly initialized. Unlike an init() method, calling valid() is entire optional. If the caller is sure that the constructor arguments have been correct, they don't need to call valid(). Note that you can still use assertions inside the class.
Anyways, for small classes like this one literally anything is better than implicitly forcing the user to allocate on the heap. The author should have pointed out the massive drawbacks of this approach.
- maccard 5y agoThat mdthod is what the author is explicitly trying to avoid - having invalid state representabld. Using optional I'd a much better solution
- spacechild1 5y agoIn the end there's not much difference between the two. In both cases you essentially call a function/operator to verify the correctness of the object. std::optional doesn't really enforce a check, it only makes it more obvious to the user. On the other hand, returning std::optional means that it will always check the invariant, whether you need it or not, so there is a potential performance penalty. Just something to be aware of.