如何在表达式中触发 std::shared_ptr 的 bool 运算符(即 `bool is_empty = shared_ptr1 && shared_ptr2;` )?

Joh*_*ohn 1 c++ smart-pointers shared-ptr c++14

鉴于cur_front_rescur_back_res都是shared_ptr, std::shared_ptr 的 bool 运算符如何在表达式(即bool is_empty = cur_front_res && cur_back_res;)中触发?

仅仅因为如果操作数(即 before和 after )不是 bool 类型,&&总是会导致内置转换?&&&&

下面的代码片段确实有效

#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;
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*Cat 5

仅仅因为如果操作数(即 before和 after )不是类型&&,总是会导致内置转换?&&&&bool

基本上是的。

bool转换有点特殊:尽管operator bools 通常是explicit(包括 for 的shared_ptr),但在少数情况下可以隐式调用它(“上下文布尔转换”)。其中包括布尔运算符的操作数、//if条件等。whilefor