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

如何正确编写返回boost::optional<EventItemCategory>的三个getter函数

问题解决方案

错误根因

  • 第一种实现报错:返回boost::optional<EventItemCategory>值类型时,需要拷贝构造boost::optional实例,其内部会拷贝存储的EventItemCategory对象,但该类的拷贝构造函数已被显式删除,因此编译失败。
  • 第二种实现报错:boost::optional<T>无法隐式转换为T类型,缺少显式解引用操作,因此类型转换失败。

最优实现方案(推荐)

返回boost::optional的const引用,既保留了可选值的语义,又完全避免了EventItemCategory的拷贝操作,不会触发被删除的拷贝构造函数:

class EventMessage
{
public:
    const boost::optional<EventItemCategory>& get_m_source() const { return m_source; }
    const boost::optional<EventItemCategory>& get_m_key() const { return m_key; }
    const boost::optional<EventItemCategory>& get_m_data() const { return m_data; }

private:
    void init();
    boost::optional<EventItemCategory>& getEventItemCategory( EVENT_ITEM_CATEGORY_TYPE const& type );

    time_t m_timestamp;
    boost::optional<PROPERTY_OPERATION> m_propertyOperation;
    boost::optional<EventItemCategory> m_source;
    boost::optional<EventItemCategory> m_key;
    boost::optional<EventItemCategory> m_data;
    std::map<EVENT_ITEM_CATEGORY_TYPE const, boost::optional<EventItemCategory> & > m_eventItemMap;
};

调用示例

EventMessage msg;
const auto& source_opt = msg.get_m_source();
if (source_opt) {
    // 可选值非空时再访问内部对象,无拷贝开销
    const EventItemCategory& source = *source_opt;
    // 业务逻辑处理
}

备选实现方案

如果你可以确保调用get方法时,对应的可选成员一定非空,也可以直接返回EventItemCategory的const引用:

const EventItemCategory& get_m_source() const {
    // 调试阶段可加断言校验非空,发布版本可移除
    assert(m_source.has_value());
    return *m_source;
}
const EventItemCategory& get_m_key() const {
    assert(m_key.has_value());
    return *m_key;
}
const EventItemCategory& get_m_data() const {
    assert(m_data.has_value());
    return *m_data;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:36:08