Hacker News new | past | comments | ask | show | jobs | submit login

This is solved in Rust by letting you test and unwrap at the same time:

    if let Some(obj) = my_optional {
        do_stuff(obj);
    }
>However if the dereferencing, my_optional, should be safe, it too would need to perform a conditional check behind the scenes. But it doesn't - as C++ places that on the programmers hand to not sacrifice speed

So basically that turns C++ optional types into fancy linter hints which won't actually improve the safety of the code much.

I understand C++'s philosophy of "you pay for what you use" but that's ridiculous, if you use an optional type it means that you expect that type to be nullable. Having to pay for a check is "paying for what you use". If you don't like it then don't make the object nullable in the first place and save yourself the test. That's just optimizing the wrong part of the problem.




You can also do it in a one-liner in C++ if you're using shared pointers:

    if(auto obj = my_weak_ptr.lock())
    {
        do_stuff(obj);
    }
> Having to pay for a check is "paying for what you use". If you don't like it then don't make the object nullable in the first place and save yourself the test.

The point is that I can choose _when_ to pay that cost (e.g. I can eat the nullability check at this point, but not at this point, and I can use more sophisticated tooling like a static analyser to reason that the null check is done correctly).

Is it more error prone? yes. Does it allow for things to horribly wrong? yes. Is "rewriting it in rust" a solution? No. If I want to pay the cost of ref-counting, I can use shared/weak ptrs.


The rust code in question is not using reference counting.


Rust's borrow checker is like compile-time reference counting. Same benefit, but no run-time cost.


> So basically that turns C++ optional types into fancy linter hints which won't actually improve the safety of the code much.

C++'s optionals are less "safer pointers" and more "stack-allocated pointers" (nor to be confused with pointers to stack allocations).


C++ gives you all the options as usual.

  do_stuff(my_optional.value())
Is also safe, it throws if the value is absent, the safety check is performed behind the scenes.

But people might not want to throw an exception, so

  if (my_optional) 
         do_stuff(*my_optional);
Must also be allowed. The consequence is someone can also just do

  do_stuff(*my_optional)
No safety check is done and you get undefined behavior if the value is absent.

I don't know rust so I suspect it has a language construct which c++ lacks that prevents you from doing

  let Some(obj) = my_optional 
  do_stuff(obj);


Yes, you have to use if let, not let. That code would be a compiler error. (Specifically, a “non-exhaustive pattern” error.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: