3 ms·
> Developers should "opt in" for unsafe instead of "opt out" of it! Why ? C++ guiding principle is zero cost abstractions.
by soulbadguy 3y ago
> Developers should "opt in" for unsafe instead of "opt out" of it!
Why ?
C++ guiding principle is zero cost abstractions.
- estebank 3y agoIt's "zero cost abstractions over what you would write by hand". If you argue that anyone doing array access should be doing bounds checks when in doubt, a C++ compiler performing bounds checks would still be considered zero(additional)-cost.
- pptr 3y agoWell, when you are not in doubt you don't want unnecessary bounds checks.
- estebank 3y agoIf you can communicate to a human that a bounds check isn't necessary, you can communicate it to a compiler.
- pptr 3y agoI'm all for better tools to help the compiler figure things out. Here is an example where I can't communicate the invariants to the compiler: ``` std::vector<int> v; ... v.push_back(2); std::sort(v.begin(), v.end()); // no need to check i < size because we know we will find value 2 somewhere in the v. for (int i = 0; i < v.size(); ++i) { if (v[i] == 2) return i; } ``` Note that in C++ you can manually mark code after the loop as unreachable, which would indeed skip the size check. But that's as bad as not checking bounds in the first place.
- soulbadguy 3y agoNo...