3 ms·
Do you mean that the purpose of std::optional is to be faster than a pointer (which could represent absence as nullptr)? I would have thought it would be ML-st
by kragen 6y ago
Do you mean that the purpose of std::optional is to be faster than a pointer (which could represent absence as nullptr)? I would have thought it would be ML-style safety, but it seems like you're right. I guess a tagged union (or std::pair<T, bool>) would be faster—if the std::pair is a local variable, fields of the wrapped object will be at fixed offsets from your stack pointer or frame pointer, so you save yourself an indexed register load the first time you access a field of the object. That seems to have been the intended use.
Why did they think this was a good idea?
- dataflow 6y agoNo, the purpose wasn't to be faster than a pointer. You can't even necessarily use a pointer where you can use std::optional; the value of std::optional is embedded in itself. One purpose would be type safety (and things revolving around that). Another would be to let you pass around an optional object just as easily as the underlying object. As to whether it's a good idea to have it at all, I'm not particularly fond of it personally either. I don't have specific issues with its dereferencing safety though. Don't confuse type safety with memory safety though. Type safety != memory safety != thread safety != ...
- kragen 6y agoAll good points. Thank you.