Switch between () and operator [] for std :: vector depending on compiler / NDEBUG
I know g ++ (and MSVC) have keys that allow bounds checking using the [] operator, unfortunately, as far as I know, LLVM libC ++ does not have a full implementation of such keys or debug code.
In my current project, I have used my own implementation of a vector (which I wrote for portability a few years ago) that does not throw exceptions and checks bindings based on the [] and operator (actually one call the other and they behave the same as there is no exceptions).
I am going to transfer this codebase after I have finished my current program and it can be used for a long time. Since I shouldn't require it to support this or anything I would rather be fully standardized around the world, and I don't feel like the re-implementation of the container is standard-compliant (I also very much doubt my container is as good as as written by libc ++ or libstdc ++ command).
Is there some kind of preprocessing magic or something that I can do to make the [] operator behave like at () during debugging (so it breaks due to an uncaught exception) and behave like the [] operator when will I disable this debug mode? (The project fully supports C ++ 14)
source to share
We can see from the trunk libc ++ source code for the vector that there is indeed such a check internally std::vector<>::operator[]
that goes through _LIBCPP_ASSERT
.
Unfortunately, libc ++ debug feature doesn't work yet .
So:
- Stay tuned for libC ++ updates.
- Train your team to wait
operator[]
to quietly accept the broken entrance. This is what it does, by definition. You have to rely on additional ad-hoc checks for specific requirements, which is a really bad idea. Your team should write their own statements if they are not sure what they are doing.
source to share
Is there some kind of preprocessing magic or something that I can do to make the [] operator behave like at () during debugging (so it breaks due to an uncaught exception) and behave like the [] operator when will I disable this debug mode? (The project fully supports C ++ 14)
Uhhh ... how about this?
const T& your_vector::operator[](std::size_t index) const
{
#ifndef NDEBUG // !! double negative condition
if(index >= size_) // assume size_ is std::size_t size_; member of class
throw std::out_of_bounds{"const T& your_vector::operator[]"};
#endif
return data_[index]; // assume data_ is a native array containing the elements
}
const T& your_vector::at(std::size_t index) const
{
if(index >= size_) // assume size_ is std::size_t size_; member of class
throw std::out_of_bounds{"const T& your_vector::at"};
return data_[index]; // assume data_ is a native array containing the elements
}
The implementation of the indexing operator is identical at
when DEBUG is defined and faster when the macro is not defined.
source to share