I am writing a class that represents a button. This button may or may not have various attributes like text written on it, shortcut, texture or flat color fill. So if for example, this button doesn't have any texture set, texture drawing process is skipped.
My first solution was to use made up default values that would say that the given attribute is unused (if alpha value of color was 0 the color fill drawing would be skipped etc.).
Other option I have is to use newly added std::optional which would be much clearer and simpler to use.
Here are the 2 mentioned examples:
class Button { void draw() { if (fill) drawRectangle(*fill); if (sprite) drawSprite(*sprite); if (font) drawText(name, *font); } std::optional<std::string> font; std::optional<std::string> sprite; std::optional<Color> fill; } class Button { void draw() { if (fill.alpha != 0) drawRectangle(fill); if (sprite != "") drawSprite(sprite); if (font != "") drawText(name, font); } std::string font; std::string sprite; Color fill; } What can the advantages and disadvatages of using std::optional be in this case? What I'm mainly interested in, are the memory usage and overhead differences.
Also should I just, instead of using if to check whether optional contains value, call value() and catch the exception?
.value()and catching the exception instead of checking if it has a value: That is a bad idea. As the name suggests, exceptions are for exceptional cases, and the overhead caused by stack unrolling isn't negligible. Assuming that a lot of buttons e.g. wont have a color, the optional being empty isn't an exceptional case at all.std::optional<std::string>as extremely useful, unless an empty string is different from no string at all.std::optionalwas intended for function returns, not class members. This is a pretty wasteful thing to do. Also, note thatsprite.empty()should be used oversprite == "".std::optionalhas memory overhead (probably something similar to additionalbool)std::optionalmay have any advantage. Also, consider major UI implementations such as AWT and .NET: an empty field is really empty, not "absent". Again, you get not value out of it.