Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

const_reference operator[](const typename object_t::key_type& key) const throw instead of assert #1039

Closed
smonasco opened this issue Apr 5, 2018 · 5 comments
Labels
solution: duplicate the issue is a duplicate; refer to the linked issue instead

Comments

@smonasco
Copy link

smonasco commented Apr 5, 2018

Feature Request

I'd rather have an out_of_range exception thrown than undefined behavior that kills my app (VS2015).

@OvermindDL1
Copy link

Except by following the standard, operator[] is unchecked where a at should be checked. I.E. accessing an invalid key/index via operator[] is supposed to be UB. If you want a checked version then you should use an at (if this library doesn't have an at then it should be added, I don't recall...).

@nlohmann
Copy link
Owner

nlohmann commented Apr 5, 2018

Duplicate: #264 #135

@nlohmann nlohmann added the solution: duplicate the issue is a duplicate; refer to the linked issue instead label Apr 5, 2018
@nlohmann
Copy link
Owner

nlohmann commented Apr 5, 2018

The behavior of const operator[] is documented. The goal is to have quick access without checking overhead. For the latter, there is at.

There have been long discussions about the behavior. In conclusion, we would rather have a const operator[] version with the current semantics than just a copy of at. We are aware of std::map not having a const operator[].

To be sure, always use at, or find in combination with operator[].

@smonasco
Copy link
Author

smonasco commented Apr 5, 2018

OK, but there are no savings in doing the assert over the if and throw. The assert still must make the comaprison.

https://ideone.com/e.js/RyHb0t

Everytime I check the assert over 1,000,000 iterations it ends up being slower actually.

@nlohmann
Copy link
Owner

nlohmann commented Apr 5, 2018

In production code, you should compile without assertions.

@smonasco smonasco closed this as completed Apr 5, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
solution: duplicate the issue is a duplicate; refer to the linked issue instead
Projects
None yet
Development

No branches or pull requests

3 participants