Gaven that cur_front_res
and cur_back_res
are both shared_ptr, how the bool operator of std::shared_ptr is trigered in the expression(i.e. bool is_empty = cur_front_res && cur_back_res;
)?
Just because &&
always cause built-in conversion if the operands(i.e. before &&
and after &&
) is not an bool type?
The code snippet below works indeed.
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> cur_front_res; // Empty shared_ptr
std::shared_ptr<int> cur_back_res(new int(42)); // Shared_ptr pointing to an int
bool is_empty = cur_front_res && cur_back_res;
if (is_empty) {
std::cout << "Both cur_front_res and cur_back_res are not empty" << std::endl;
} else {
std::cout << "Either cur_front_res or cur_back_res is empty" << std::endl;
}
return 0;
}
Just because
&&
always cause built-in conversion if the operands(i.e. before&&
and after&&
) is not anbool
type?
Basically yes.
But the bool
conversion is somewhat special: even though operator bool
s are usually explicit
(including the one for shared_ptr
), there are a few cases where it can be called implicitly ("contextual bool conversion"). Among other things, those include operands of boolean operators, if
/while
/for
conditions, etc.