为什么我不能使用 nullptr
而不是 nullopt
?为什么 {}
翻译成 nullopt
?
最佳答案
Why can't i use
nullptr
instead ofnullopt
?
因为它们是不同的东西。它们意味着不同的东西,并且它们用于不同的东西。
必须有一个独特的 nullopt
值才能与 std::optional
一起使用,因为 nullptr
已经做了一些事情:
std::optional<int*> o;
o = nullptr;
assert( o.has_value() );
o = std::nullopt;
assert( !o.has_value() );
And why
{}
translates likenullopt
?
(请注意,这仅适用于 std:optional
,而不适用于将 {}
与其他类型一起使用时。)
它这样做是因为能够说 o = {}
并让它做正确的事情™ 很方便,所以 std::optional
的规范是编写使其工作。
关于c++ - nullptr、{} 和 nullopt 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47791737/