我们是否有更好的方法来返回C++中的抽象类
Do we have a better way of returning abstract classes in C++?
我想开始在我的C++代码中加入一些接口,以便我更容易使用模拟进行单元测试。
这样做的问题是从C++的方法返回抽象类是一种痛苦。不能按值返回,因此需要返回指针或引用。
考虑到过去六七年来C++的所有发展,我想我会问我们是否有更好的方法来返回抽象基类。没有噪音的界面看起来像这样,但我相信这是不可能的。
IBaseInterface getThing() {return DerivedThing{};}
我记得过去这样做的方式是使用指针(现在可能是智能指针):
std::unique_ptr<IBaseInterface> getThing() {return std::make_unique<DerivedThing>();}
指针的问题在于我从未真正打算利用 nullptr,因此处理指针而不是值的开销和噪音使我作为读者没有任何价值。
有没有我不知道的更好的方法来处理这个问题?
编辑:提供完整的示例,包括使多态句柄可复制。
#include <iostream>
#include <utility>
#include <memory>
struct IBaseInterface {
IBaseInterface() = default;
IBaseInterface(IBaseInterface const&) = default;
IBaseInterface(IBaseInterface &&) = default;
IBaseInterface& operator=(IBaseInterface const&) = default;
IBaseInterface& operator=(IBaseInterface &&) = default;
virtual ~IBaseInterface() = default;
virtual std::unique_ptr<IBaseInterface> clone() const = 0;
virtual void do_thing() = 0;
};
struct handle
{
handle(std::unique_ptr<IBaseInterface> ptr)
: _impl(std::move(ptr))
{}
handle(handle const& r)
: _impl(r._impl->clone())
{}
handle(handle && r)
: _impl(std::move(r._impl))
{}
handle& operator=(handle const& r)
{
auto tmp = r;
std::swap(_impl, tmp._impl);
return *this;
}
handle& operator=(handle && r)
{
_impl = std::move(r._impl);
return *this;
}
// interface here
void do_thing() { _impl->do_thing(); }
private:
std::unique_ptr<IBaseInterface> _impl;
};
struct DerivedThing : IBaseInterface
{
std::unique_ptr<IBaseInterface> clone() const override
{
return std::make_unique<DerivedThing>(*this);
}
void do_thing() override
{
std::cout << "I'm doing something" << std::endl;
}
};
handle make_thing()
{
return handle(std::make_unique<DerivedThing>());
};
int main()
{
auto a = make_thing();
auto b = a;
a.do_thing();
b.do_thing();
return 0;
}
现在使用句柄,就好像它有(可移动的)值语义一样
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 为什么模板类中的对象不能返回值