lmi
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [lmi] Parallel blues


From: Vadim Zeitlin
Subject: Re: [lmi] Parallel blues
Date: Wed, 21 Jun 2017 14:50:05 +0200

On Wed, 21 Jun 2017 12:26:36 +0000 Greg Chicares <address@hidden> wrote:

GC> The problem with pointers is that we must check whether they're null
GC> before each use, or disaster occurs.
GC> 
GC> The problem with std::optional is the problem with pointers.

 An important difference is that it's pretty common to use pointers without
checking that they're not null first, making it very difficult to find
places where such checks are really needed. With std::optional<> any code
using it without checking for its validity first is immediately suspicious
and so bugs due to dereferencing it wrongly are rare in practice.

 Also, std::optional<> does have value() method which avoids undefined
behaviour, so saying that std::optional<> is as unsafe as raw pointers is a
bit like saying that std::vector<> is as unsafe as raw arrays because it
has an unsafe operator[] -- while forgetting that it also has a safe at()
method. And to continue this analogy, std::vector<> also provides API which
ensures safety of iterating over it at compile-time using range-for loops
in C++11, which is similar to std::optional::value_or() which also
guarantees safety.

 But, of course, if you really want to avoid the billion dollar problem of
having NULL in the first place, you need to use another language and you
won't be surprised that a huge part of appeal of Rust to me is that it
really does solve this problem once and for all, making it impossible to
write code dereferencing an invalid pointer or optional value (well, to be
precise, it's still possible to write it, it's just impossible to compile
it :-).

GC> Then I realized that I could implement
GC>   bool is_null_stream(std::ostream&);
GC> and use that to conditionalize stream output in 'zero.hpp', and its
GC> effect on calendar_date_test's speed is the same as using #ifdef.

 For me this solution is less than ideal. Forgetting to check for
std::optional<std::ostream> validity before using it would result in an
exception (if you use value(), as you should) and even with raw pointers
dereferencing a null pointer is a relatively nice bug to have, as it's so
easily diagnosable. OTOH, forgetting to use is_null_stream() will almost
certainly go unnoticed and just result in much poorer performance during
run-time, even in production code. This doesn't seem like a good trade off
to me.

 Regards,
VZ


reply via email to

[Prev in Thread] Current Thread [Next in Thread]