You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

std::shared_ptr的bool运算符在&&表达式中的触发机制及原因咨询

问题:std::shared_ptr在逻辑与表达式中的bool运算符触发机制

已知cur_front_res和cur_back_res均为std::shared_ptr类型,请问在表达式bool is_empty = cur_front_res && cur_back_res;中,std::shared_ptr的bool运算符是如何被触发的?是否因为当&&的操作数非bool类型时,总会触发内置转换?

可运行代码片段:

#include <iostream>
#include <memory>

int main() {
    std::shared_ptr<int> cur_front_res; // 空的shared_ptr
    std::shared_ptr<int> cur_back_res(new int(42)); // 指向int对象的shared_ptr

    bool is_empty = cur_front_res && cur_back_res;

    if (is_empty) {
        std::cout << "cur_front_res和cur_back_res均非空" << std::endl;
    } else {
        std::cout << "cur_front_res或cur_back_res为空" << std::endl;
    }

    return 0;
}

回答

std::shared_ptr类重载了显式的bool转换运算符(C++11及以后标准),这个运算符会在需要将智能指针转换为bool类型的上下文中被触发。

在&&逻辑与运算场景中,逻辑运算符的操作数会被要求转换为bool类型——这是逻辑运算的上下文规则决定的,并非所谓“非bool操作数总会触发内置转换”。此时会执行标准转换序列,其中就包含了shared_ptr提供的用户定义转换:调用bool运算符判断该智能指针是否持有有效的非空对象。

针对表达式cur_front_res && cur_back_res的执行流程:

  • 先对cur_front_res执行bool转换:若它是空指针,转换结果为false,逻辑与运算会直接短路,不再计算cur_back_res;
  • 若cur_front_res非空(转换结果为true),才会继续对cur_back_res执行bool转换,最终将两者的逻辑与结果赋值给is_empty。

另外需要注意,shared_ptr的bool转换是显式的,这意味着它不能被隐式转换为其他数值类型(比如不能直接写int x = cur_front_res;),但逻辑运算、if条件判断这类需要bool值的上下文会正常触发这个显式转换。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:05:15