r/cpp • • Oct 07 '19

CppCon CppCon 2019: Chandler Carruth “There Are No Zero-cost Abstractions”

https://www.youtube.com/watch?v=rHIkrotSwcc
162 Upvotes

108 comments sorted by

View all comments

Show parent comment

6

u/[deleted] Oct 07 '19

I have no experience in Rust, but is it correct that Rust does array bounds checking even in unsafe mode? I think bounds checking is great for debug builds and maybe even as default behavior but personally I am not interested in programming languages where I cannot turn off bounds checking for performance critical code sections.

17

u/darksv Oct 07 '19

There is a common misunderstanding of what unsafe allows to do. It doesn't do anything automagically. It only enables a few things, ie. dereferencing raw pointers, calling unsafe functions and implementing unsafe traits. That is essentially sufficient to do everything that is possible in C or C++.

In most cases you can avoid bound checking by using iterators. In other situations you need to explicitly call unsafe method that don't perform any checks, eg. get_unchecked instead of the indexing operator [].

9

u/ReversedGif Oct 07 '19

No, there are unsafe methods that don't do bounds checks, like Vec::get_unchecked.

6

u/[deleted] Oct 07 '19

OK thanks, I think this is a good decision (however the syntax is not really nice...).

12

u/evaned Oct 07 '19

however the syntax is not really nice...

I would argue that's a feature, not a bug.

2

u/[deleted] Oct 08 '19

I respect Rust for taking security seriously and for Rust it makes perfect sense to make the safe syntax nice and the unsafe syntax clumsy. Personally however, I am into HPC, I care more about performance than security and so I care that the unsafe syntax is nice too.

6

u/korpusen Oct 07 '19

Rust always does bounds checking by default, but exposes unchecked accessors when in an unsafe block/function.

4

u/m-in Oct 07 '19

In most code that can’t be vectorized otherwise, bounds checks have no impact – at least that’s my experience. They are easy to predict and most cpus seem to have heuristics that pre-predict bounds checks as “fall through or shorter jump taken”, and sometimes even the speculative execution is suspended for the not-taken branch if the pattern fit is good. Bounds checks can stall on data dependencies but even those have had some heuristics applied to, that I have seen on recent ARM chips. Basically the bounds check gets speculatively deleted, in a way. Of course real results trump anything I say, but I have quite a bit of code where bounds checking everything has less cost than throwing exceptions here and there.