Is using bitset::operator[] equivalent to using bitset::test or is there some underlying optimization?
That is, are these two loops equivalent?
Using bitset::operator[]:
static const int UP = 0;
static const int DOWN = 1;
for(int i = 1; i < KEY_MAX; ++i) {
if(_handler && (_prevKey[i] == UP && _curKey[i] == DOWN)) {
_handler->EnqueueEvent(new KeyboardKeyDownEvent(i));
}
if(_handler && (_prevKey[i] == DOWN && _curKey[i] == DOWN)) {
_handler->EnqueueEvent(new KeyboardKeyPressEvent(i));
}
if(_handler && (_prevKey[i] == DOWN && _curKey[i] == UP)) {
_handler->EnqueueEvent(new KeyboardKeyUpEvent(i));
}
}
Using bitset::test():
static const bool UP = false;
static const bool DOWN = true;
for(int i = 1; i < KEY_MAX; ++i) {
if(_handler && (_prevKey.test(i) == UP && _curKey.test(i) == DOWN)) {
_handler->EnqueueEvent(new KeyboardKeyDownEvent(i));
}
if(_handler && (_prevKey.test(i) == DOWN && _curKey.test(i) == DOWN)) {
_handler->EnqueueEvent(new KeyboardKeyPressEvent(i));
}
if(_handler && (_prevKey.test(i) == DOWN && _curKey.test(i) == UP)) {
_handler->EnqueueEvent(new KeyboardKeyUpEvent(i));
}
}
From the C++03 standard, §23.3.5.2/39-41:
§23.3.5.2/46-48:
§23.3.5.2/49-51:
So when the object is
const, they return the same value, excepting that whenposis invalidtestthrowsout_of_rangewhileoperator[]throws nothing. When the object is notconst, the operator returns a proxy object allowing one to mutate the object’s data.