3 ms·
So your constructor has to be infallible. That means either you can't allocate memory in your constructor, or that all classes that are backed by dynamic memory
by notriddle 8y ago
So your constructor has to be infallible. That means either you can't allocate memory in your constructor, or that all classes that are backed by dynamic memory have to have a tacked-on error state in case the constructor "fails".
An operating system can't just crash if memory allocation fails, because it's actually normal for the operating system to run out of memory. If your OS is even a little bit like Windows 95 or System V, it uses all of the "left-over" memory for the file system cache, so every time it tries to allocate memory, it probably needs to flush a page to disk, which takes long enough that the OS will also want to go back into the scheduler to try to find some more work to do while that runs.
Ironically enough, C++ has fallible allocation in the standard library in spite of being ill-suited for it (unless you have exceptions; those can support fallible allocation just fine), while Rust went with the let-it-crash approach in its standard library, despite the fact that the language itself allows you to just return an Option from all the functions that allocate memory.
- mehrdadn 8y agoI was just saying you can have an error state, like iostreams already do. It doesn't imply you give up RAII.