小编Mic*_*sov的帖子

我可以以某种方式返回 std::Optional 并带有对我的数据的 const 引用以避免复制它吗?

假设我有一些基类,它可以选择返回一些特定的数据。它还为我提供了“hasData”函数来检查此类特定数据是否可供使用

class MyClassBase {
public:
    virtual bool hasData() const { return false; }
    virtual const Arg1& getData() const { throw std::runtime_error("No data");  }
};

class MyClassDerived: public MyClassBase {
    Arg1 m_data = Arg1(10);
public:
    bool hasData() const override { return true; }
    // Good - no copy constructor for data as I want
    const Arg1& getData() const override { return m_data; }
};
Run Code Online (Sandbox Code Playgroud)

这效果很好并且达到了我想要的效果。但是“hasData”和“getData”是很好的候选者,可以用一个返回“std::optional”的函数来替换。但是当我尝试改进返回 std::Optional 的 API 时,我意识到我无法再将“常量引用”返回到我的内部数据

class MyClassWithOptBase {
public:
    virtual std::optional<Arg1> getData() const { return std::nullopt; } …
Run Code Online (Sandbox Code Playgroud)

c++ stl c++17 stdoptional

5
推荐指数
1
解决办法
6215
查看次数

标签 统计

c++ ×1

c++17 ×1

stdoptional ×1

stl ×1