如何正确编写返回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
相关产品推荐
相关产品推荐

