问题描述
从远古时代开始,当将指针传递给函数或从函数传递指针时,我们倾向于对空指针进行特殊处理:
From time immemorial, when passing pointers to or from functions, we tend to special-case the null pointer:
p = get_pointer_to_the_foo(args);
if (p == nullptr) { /* foo is inaccessible, do one thing */ }
else { /* we can access foo, do something else */ }
,这是从C继承的.现在,我们偶尔会对其他类型执行相同的操作,例如使用带符号的类型表示有效的非负值,例如-1或表示错误.
and this is an inheritance from C. Now, we occasionally would do the same with other types, e.g. using a signed type to represent either a valid non-negative value, and, say, -1 or to indicate an error.
现在将开始使用std::optional
最终弃用后一种模式:std::optional<unsigned>
是nullopt
或非负值.但是-指针呢?毕竟,nullptr
只是无数无效指针值之一.因此,在编写新代码时(全部都是C ++ 17时)-我们是否应该从本质上忘记它,而绕过std::optional<foo_t*>
或假定非空foo_t *
呢?
The latter pattern will now be finally deprecated with the onset of std::optional
: std::optional<unsigned>
is either nullopt
or a non-negative value. But - what about pointers? After all, nullptr
is just one of innumerable invalid pointer values. So, when writing new code (when all of it is C++17) - should we essentially forget about it, and pass around either std::optional<foo_t*>
's or assumed-non-null foo_t *
's?
推荐答案
Pointer已经嵌入了可选语义.因此std::optional<T*>
至少可以说是多余的,并且该功能的引入不会对很多原始指针产生影响.
Pointer embed the optional semantic already. Therefore std::optional<T*>
would be redundant to say the least and the introduction of said feature won't impact much raw pointers.
对于std::unique_ptr
,std::shared_ptr
和std::weak_ptr
也是如此,所有这些也可以是nullptr
.
This is also true with std::unique_ptr
, std::shared_ptr
and std::weak_ptr
all of which can also be nullptr
.
就像使用任何新功能一样,我们必须思考什么是实用的,而不是我们天生的在可行的地方使用它的冲动.
Just like with any new feature we have to ponder what's pragmatic versus our innate urge to use it everywhere it's feasible.
这篇关于使用std :: optional标准化,我们可以停止在新代码中使用nullptr并弃用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!