在C ++中代表Nullable成员的最佳方法? [英] Best way to represent Nullable member in C++?
问题描述
可能重复:
在C ++中为空值
代表空值的最佳方法是什么
What is the best way to represent nullable member in C++?
在C#中,我们可以使用 Nullable< T>
类型。非常需要这种数据类型,因为并非所有内容都可以具有有意义的值。数据类型是如此重要,以致 @Jon Skeet 花费了整整一整章的篇幅,涉及27页,仅描述了 Nullable< T>
在他的杰出著作 C#in Depth 中。
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.
一个简单的示例可以是 Person
class 1 ,定义为:
One simple example can be a Person
class1, defined as:
struct Person
{
std::string Name;
DateTime Birth;
DateTime Death;
//...
};
由于一个人总是有生日,所以出生$ c $上述类的c>成员将始终具有一些有意义的值。但是
死亡
怎么样?如果这个人还活着,那应该值什么呢?在C#中,可以将该成员声明为 Nullable< DataTime>
2 ,可以将其分配为 null
如果该人还活着。
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.
在C ++中,解决此问题的最佳方法是什么?到目前为止,我只想到一种解决方案:将成员声明为 pointer :
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;
现在当它的值可以是 nullptr
人还活着。但这会强制对死者使用 new
,因为它将具有一定的合法价值。反过来,这意味着不能依赖编译器生成的 default 复制语义代码。程序员必须遵循三个规则来编写复制构造函数,复制分配,析构函数。(C ++ 03),或者在C ++ 11中,五个规则。
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。其他示例包括关系数据库表,因为在许多DBMS中,列可以为空。
2。这也有一个简写。可以编写 DataTime?
,它与 Nullable< DateTime>
完全相同。
2. There is also a shorthand for this. One can write DataTime?
which is exactly same as Nullable<DateTime>
.
推荐答案
您可以查看 Boost.Optional :
struct Person
{
std::string Name;
DateTime Birth;
boost::optional<DateTime> Death;
//...
};
- 您的
死亡
首先是未初始化的。 - 然后可以使用
=
为其分配值,例如死亡= myDateTime
。 - 当
Death.is_initialized()
时,可以使用>
。 - 使用
Death.reset()
再次取消初始化。 - Your
Death
is "uninitialised" at first. - You can then assign a value to it with
=
, likeDeath = myDateTime
. - When
Death.is_initialized()
, you can useDeath.get()
. - Uninitialise it again with
Death.reset()
.
不过,对于像这样的简单情况,通常认为只选择自己的公然值(例如 DateTime
的 0000-00-00 00:00:00。
For simple cases like this, though, it's usually considered more coherent to just pick your own blatant sentinel value like, say, a DateTime
of "0000-00-00 00:00:00".
这篇关于在C ++中代表Nullable成员的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!