简体   繁体   中英

Optimizing std::bitset with noexcept

I have some code which needs to check if a bit in a bit field is set. I've been impressed with how optimized std::bitset.count compiles down, so thought this would be a good use of it as well. I'm surprised that when I use bitset.test, the compiler is still checking for exceptions, even when I add noexcept.

I have other checks to ensure that I won't test a bit which is out of range. Is there anything else I can do to optimize this code?

bool bitset_test(int n, size_t m) noexcept {
    // The caller already verifies m is within range
    return std::bitset<64>( n ).test( m );
}

Compiled output: https://godbolt.org/g/uRggXD

Is there anything else I can do to optimize this code?

Yes! Just like other containers, std::bitset has a function to get a specific bit with and without bounds checking. test is the bounds checking function, which throws.

But if you have other tests to make sure that m is not too high, then you can use std::bitset 's operator[] , which doesn't have any exception handling in the resulting assembly , because it assumes that you are passing a correct value:

bool bitset_test(int n, size_t m) noexcept {
    return std::bitset<64>(n)[m];
}

As others have mentioned, the reason why the compiler still generates exceptions in the resulting assembly is because the compiler still has to call std::terminate if an exception is thrown, so it can't just ignore the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM