Post Self
Post Self

Reputation: 1554

Initialize Variables as Empty

When I have an unsigned int, but I want to find out if it is empty or not, but I need 0, I always declare it as an int and set it to -1. What am I supposed to do, though, when I need the full number spectrum or I am even working with float/double?

With some data-types it is simple, for example std::string which you can just compare to "", but is there a function to check if a variable is empty regardless of data-type, even of custom class objects?

Upvotes: 0

Views: 3762

Answers (1)

Rob Hall
Rob Hall

Reputation: 2823

The semantics of a value being missing are exactly why std::optional was introduced to the C++ language specification.

std::optional<unsigned int> value; // by default, the value is missing
if(value) {
    // executed if the value is present, it is not
} else {
    // this code is executed
}
value = 1;
if(value) {
    // This code would now be executed
    std::cout << "the value: " << *value << std::endl;
}

This requires a change in thinking regarding the meaning of the variable, but it forces you to think at all times regarding whether or not the variable would be present.

So for example, if you had your own class type MyClass and you wanted to retain a, potentially missing, instance of it, you would do so as follows:

std::optional<MyClass> obj; // Initially missing
obj = MyClass();            // Assigns a newly-created instance of MyClass
obj->foo();                 // Calls the 'MyClass::foo' method
obj.reset();                // clears the 'obj' optional

Upvotes: 2

Related Questions