Possible Duplicate:
Nullable values in C++
What is the best way to represent nullable member in C++?
In C#, we can use Nullable<T>
type. Such a data type is very much needed as not everything can have meaningful value. It is so important data type that @Jon Skeet has spent one entire chapter, spanned over 27 pages, describing only Nullable<T>
in his outstanding book C# in Depth.
One simple example can be a Person
class1, defined as:
struct Person
{
std::string Name;
DateTime Birth;
DateTime Death;
//...
};
As a person always have birthdate, so the Birth
member of the above class will always have some meaningful value. But how about Death
? What should it value be if the person is alive? In C#, this member can be declared as Nullable<DataTime>
2 which can be assigned with null
if the person is alive.
In C++, what is the best way to solve this? As of now, I've only one solution in mind: declare the member as pointer:
DataTime *Death;
Now its value can be nullptr
when the person is alive. But it forces the use of new
for dead person, as it's going to have some valid value. It in turn implies one cannot rely on the default copy-semantic code generated by the compiler. The programmer has to write copy-constructor, copy-assignment, destructor following rule of three (C++03), Or in C++11, rule of five.
So do we have any better, elegant solution to this problem than just making it pointer?
1. Other examples include relational database tables, as in many DBMSs columns can be nullable.
2. There is also a shorthand for this. One can write DataTime?
which is exactly same as Nullable<DateTime>
.