Why doesn't C++ detect when out of range vector elements are accessed with the [ ] operators by default? -
i understand arrays primitive class , therefore not have built in methods detect out of range errors. however, vector class has built in function .at() detect these errors. using namespaces, can overload [ ] symbols act .at() function throwing error when value out of vector's range accessed. question this: why functionality not default in c++?
edit: below example in pseudocode (i believe - correct me if needed) of overloading vector operator [ ]:
item_type& operator[](size_t index) { // verify index legal. if (index < 0 || index >= num_items) { throw std::out_of_range ("index operator[] out of range"); } return the_data[index] }
i believe function can written user-defined namespace , reasonably easy implement. if true, why not default?
for that's cheap []
, bounds checking adds significant overhead.
consider
int f1(const std::vector<int> & v, std:size_t s) { return v[s]; }
this function translates just 3 lines of assembly:
movq (%rdi), %rax movl (%rax,%rsi,4), %eax ret
now consider bounds-checking version using at()
:
int f2(const std::vector<int> & v, std:size_t s) { return v.at(s); }
this becomes
movq (%rdi), %rax movq 8(%rdi), %rdx subq %rax, %rdx sarq $2, %rdx cmpq %rdx, %rsi jae .l6 movl (%rax,%rsi,4), %eax ret .l6: pushq %rax movl $.lc1, %edi xorl %eax, %eax call std::__throw_out_of_range_fmt(char const*, ...)
even in normal (non-throwing) code path, that's 8 lines of assembly - 3 times many.
Comments
Post a Comment