Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventing for coloring the object.
I didn't want to set this color has a pointer, because it would be necessary to delete it on every setter and on the deconstructor. Is this a bad thought?
Code:
static const Color& noneColor = Color();
static bool isNoneColor(const Color& color) {
return std::addressof(noneColor) == std::addressof(color);
}
MyShape:MyShape() {
this->color = noneColor; // this->color is an object of Color
}
void MyShape::setColor(const Color& newColor)
{
this->color= newColor;
}
void MyShape::draw()
{
if(!isNoneColor(this->color))
// Color shape
}
//different scope/class
void B::setColorForShape()
{
Color color = Color(255,255,255);
a->setColor(color);
// Calling isNoneColor(a->color); should return false;
// After this function ends does variable a->color have undefined behavior?
}
void B::setNoneColorForShape()
{
a->setColor(noneColor);
//Calling isNoneColor(a->color); should return true;
}
Is it safe to call isNoneColor with a->color afterwards the method ends?
Edit:
MyShape:color is declared has Color& color. I want to be able to set a noneColor state on my object MyShape. With a simple Color object I can't know if that color is "null"/empty state.