We just know from experience that while you may be sure right now, such an invariant is really difficult to maintain over the course of a codebase’s lifetime. The next person, the reviewer, and yourself in 3 months will have to figure out if it holds, and there’s no way to write tests for it, because it’s UB.
Meanwhile, compilers are able to optimize out the check in exactly all the cases that are also easy to verify for humans. It’s just … unnecessary.
That really depends on what you're doing. In some random function it might be tricky, but if you have it as part of a class it's not unreasonable. For example if you have a class that wraps around two or more inplace_vectors you only really need to have the check on the first member, since all members are assumed to have the same size. Or lets say you have one or more fixed size ranges and you need to gather some of their values in an inplace_vector. You can set the capacity of the inplace_vector to be the sum of the sizes of each input range. That way you actually can't end up trying too insert too many elements because you don’t even have that many elements to begin with.
Of course you don't use something like that in a difficult to maintain part of your codename where you can't actually be sure about the neccessary size of your inplace_vector or where it's easy to make mistakes, but not every function is like that. And if actually do use it in a class like I proposed earlier, it becomes a lot easier to write tests for it.
The question you should be asking is “does it ever make a difference, and is that difference worth the risk”. Most inexperienced C++ developers underestimate that risk, and overestimate the cost of a bounds check by many orders of magnitude.
Anyone who is unaware of the price of reckless amounts of UB in C++ code, I would say has never actually delivered software written in C++ with any kind of stakes on the table.
The price of the mistakes themselves is one thing. Another thing is the price of avoiding them, paying very intelligent people to spend much longer to deliver much less.
0
u/simonask_ 5d ago
We just know from experience that while you may be sure right now, such an invariant is really difficult to maintain over the course of a codebase’s lifetime. The next person, the reviewer, and yourself in 3 months will have to figure out if it holds, and there’s no way to write tests for it, because it’s UB.
Meanwhile, compilers are able to optimize out the check in exactly all the cases that are also easy to verify for humans. It’s just … unnecessary.