假设我有一些基类可以选择返回一些特定的数据。它还为我提供了“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; }
};
这很好用,可以做我想要的。但是 'hasData' 和 'getData' 是很好的候选者,可以被一个返回 'std::optional' 的函数替换。但是当我尝试改进返回 std::optional 的 API 时,我意识到我不能再向我的内部数据返回“const 引用”
class MyClassWithOptBase {
public:
virtual std::optional<Arg1> getData() const { return std::nullopt; }
};
class MyClassWithOptDerived: public MyClassWithOptBase {
Arg1 m_data = Arg1(10);
public:
// Bad - copy constructor is created for my data!
std::optional<Arg1> getData() const override { return m_data; }
// std::optional<const Arg1 &> - doesn't compile as references are not allowed
// const std::optional<Arg1> & - can't return reference to temporary object
};
一种可能性是使用std::optional<Arg1> m_data
MyClassWithOptDerived - 但它对我来说看起来不太好 - 派生类肯定有数据,并且没有理由在其中存储 std::optional 。还需要将“m_data”移动到我绝对不想要的基类
在此类示例中使用 std::optional 并避免复制数据的任何其他可能性?
PS:我检查了一些文章,例如std::optional 专门化的引用类型,似乎无法避免数据复制,我可能应该在这里使用“旧式”界面。
更新: 谢谢大家这么快的回复。对我有用的解决方案是使用 std::reference_wrapper。解决方案代码看起来像
class MyClassWithOptBase {
public:
virtual std::optional<std::reference_wrapper<const Arg1>> getData() const {
return std::nullopt;
}
};
class MyClassWithOptDerived : public MyClassWithOptBase {
Arg1 m_data = Arg1(10);
public:
// Good as well - no copy constructor for my data!
std::optional<std::reference_wrapper<const Arg1>> getData() const override {
return m_data;
}
};
// In 'main'
MyClassWithOptDerived opt;
auto res = opt.getData();
//Then res->get() will return me 'const Arg1&' as I want and no copy constructor will be invoked