如何分配“无"?到std :: optional< T> ;? [英] How to assign "nothing" to std::optional<T>?
问题描述
在阅读 std::optional
时,我很困惑将 something 和 nothing 的值分配给optional
的标准方法.
Reading about std::optional
, I'm confused about what is the standard way to assign a value of something and nothing to an optional
.
我想operator=
将是为可选值分配值的标准机制.似乎可以工作.这是否意味着基础对象的副本?
I guess operator=
would be the standard mechanism to assign a value to an optional. Seems to work. Does this imply a copy of the underlying object?
什么都不分配的标准方法是什么?我看过x = {}
(对我来说这没有意义,因为{}
是一个空块)和x = std::nullopt
.
What is the standard method to assign nothing? I've seen x = {}
(which makes no sense to me as {}
is an empty block) and x = std::nullopt
.
推荐答案
我不会说有一种标准"方式,不向std :: optional分配任何内容.
I wouldn't say there is one "standard" way to assign nothing to std::optional.
如果您阅读了std::optional
("A建议添加一个实用程序类来表示可选对象"),作者以这种方式提出了两种方式:
If you read the proposal for std::optional
("A proposal to add a utility class to represent optional objects") the authors present two ways, in this order:
我们在标准语中添加了额外的要求,以确保以下语法可用于重置可选内容:
We put the extra requirements in the standardese to make sure that the following syntax works for resetting the optional:
op = {};
我们认为这将成为在C ++中重置(进入默认构造状态)值的常见习惯用法
We consider that this will become a common idiom for resetting (putting into default-constructed state) values in C++
请注意,这不是脱离可选对象的唯一方法.您还可以使用:
Note that it is not the only way to disengage an optional object. You can also use:
op = std::nullopt;
std::optional::reset
在编写该提案时不存在,因此没有提及,但这也是一种有效的实现方式.
std::optional::reset
did not exist at the time of writing that proposal, so it was not mentioned, however it is also a valid way to do it.
这篇关于如何分配“无"?到std :: optional< T> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!