2 ms·
> This is especially problematic with the RAII pattern. Because resource acquisition can fail, you have to allow for "broken" objects to be returned, which repr
by jcelerier 9y ago
> This is especially problematic with the RAII pattern. Because resource acquisition can fail, you have to allow for "broken" objects to be returned, which represent the resource not being acquired. In functional programming, this is done with sum types (and in general way with Maybe, for instance).
... but with RAII you can't have invalid objects (if you actually care about your invariants of course).
If you do ::
class my_positive_int {
int m_x{};
public:
my_class(int x) {
if(x < 0)
throw invariant_broken;
m_x = x;
}
int get() const { return m_x; }
void set(my_positive_int other) { m_x = other.m_x; }
};
then at no point in your program, cue undefined behaviour such as reinterpreting the bytes of your class as something else, can you have a my_positive_int with x < 0.