什么时候使用可选<not_null<T*>>

jan*_*vak 6 c++ notnull stdoptional

我正在简单地阅读参考文献,并进入了讨论使用可选参考文献的部分。赫伯给出避免的原因之一optional<T&>是因为这些情况可以“同样很好地代表optional<not_null<T*>>

我很困惑你什么时候会想要optional<not_null<T*>>。在我看来,optional取消已经结束了not_null,那么在这种情况下为什么不直接使用原始指针呢?

Cal*_*eth 1

T*没有任何成员函数,而optional<not_null<T*>>有很多。

我想要的是能够编写类似的函数

auto result = maybe_A()
    .transform(A_to_B)
    .and_then(B_to_opt_C)
    .or_else({});
Run Code Online (Sandbox Code Playgroud)

这应该相当于

optional<A&> first = maybe_A();
optional<B&> second = first.transform(A_to_B);
optional<C&> third = second.and_then(B_to_opt_C);
C result = third.or_else({});
Run Code Online (Sandbox Code Playgroud)

对于指针,我们无法将其作为一个表达式来做到这一点。

A* first = maybe_A();
B* second = first ? A_to_B(*first) : nullptr;
C* third = second ? B_to_opt_C(*second) : nullptr;
C result = third ? *third : {};
Run Code Online (Sandbox Code Playgroud)

而至少optional<not_null<T*>>我们可以调整我们的功能

optional<not_null<A*>> first = maybe_A();
optional<not_null<B*>> second = first.transform([](not_null<A*> a){ return &A_to_B(*a); });
optional<not_null<C*>> third = second.and_then([](not_null<B*> b){ return B_to_opt_C(*b); });
C result = third.or_else({});
Run Code Online (Sandbox Code Playgroud)

又名

auto result = maybe_A()
    .transform([](not_null<A*> a){ return &A_to_B(*a); })
    .and_then([](not_null<B*> b){ return B_to_opt_C(*b); })
    .or_else({});
Run Code Online (Sandbox Code Playgroud)