- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个抽象基类,有几个具体的派生类;这些类都不管理任何资源。
#include <memory>
#include <vector>
// this is a pure abstract class that contains no resources
class Base {
public:
Base() {};
virtual int doSomething() = 0;
};
class Derived : public Base {
public:
Derived() {};
// this mutates the derived class
int doSomething() override { return 0; };
};
class Derived2 : public Base {
public:
Derived2() {};
// this mutates the derived class
int doSomething() override { return 0; };
};
我有一个返回随机派生实例(Derived1、Derived2、Derived3,取决于随机数抛出)的函数。
std::unique_ptr<Base> randomDerivedInstance() {
// pick a random number here and return Derived1 or Derived2 etc.
// for the purpose of this problem, I'm just returning a fixed derived class
return std::make_unique<Derived>();
}
我有一个结构,我想将这个派生实例存储在
struct DataStruct {
// this can contain Derived1 or Derived2
std::unique_ptr<Base> base;
// other things in struct omitted for clarity
// obviously this won't work
DataStruct(std::unique_ptr<Base> base) : base(base) {};
};
我从我的随机函数返回一个唯一的指针,并想将一个拷贝保存到结构中,然后调用 doSomething
对类内部执行几个变异操作,但我没有不希望它们影响存储在列表中的拷贝。
如果我知道派生实例的类型,我会使用复制构造函数创建一个新实例并将其添加到 vector 中,但在这种情况下我不知道我正在尝试的实例的具体类型添加,所以我不知道要使用哪个特定的构造函数。
int main() {
// I want to create a vector of random instances
std::vector<DataStruct> list;
// I create a random instance
auto myDerived = randomDerivedInstance();
// and I want to push a copy of myDerived before I do something with it
// obviously this doesn't work because its a unique_ptr
// what can I do here?
list.push_back(DataStruct(myDerived));
// do something that mutates myDerived
myDerived->doSomething();
// I don't want my mutations to myDerived to affect the list copy
}
由于明显的原因,上面的代码没有编译,因为我试图在 DataStruct
构造函数中分配一个 unique_ptr
。
为了使其按预期工作,我需要对此架构和代码进行哪些更改?即,将随机派生实例的值拷贝添加到结构中,以便我可以改变原始实例(反之亦然,添加原始实例并改变拷贝)。
提前感谢所有帮助!
最佳答案
在类Base
中添加一个虚成员函数clone
:
virtual auto clone() const
-> std::unique_ptr<Base>
= 0;
在每个派生类 Derived
中覆盖它以提供派生类特定的克隆:
auto clone() const
-> std::unique_ptr<Base>
override
{ return std::unique_ptr<Base>( new Derived{ *this } ); }
有可能以更高级的方式执行此操作,如果您在编译时知道派生程度最高的类,则可以静态地获得该类型的克隆,但看起来您并不需要它。
免责声明:现成的代码,未经编译器审查。
很久以前,clone
函数被称为虚拟构造函数,这个术语在 the FAQ item about this 中使用过。 .我认为它是由 Coplien 引入的。当前的常见问题解答文本没有说明。
同样值得注意的是:在 C++11 及更高版本中,clone
函数实现的生成可以通过 Derived
继承自一个实现而部分自动化,而该实现又继承自 Base
,带有构造函数参数的转发。
C++03 不支持转发,因此不得不使用代码生成宏(邪恶但实际上是当时唯一真正的解决方案)、通过虚拟继承层次结构中的支配实现继承(极其复杂和丑陋的),或者像我们现在在 C++11 及更高版本中做的那样,但使用 Do-It-Yourself 参数转发方案(有点任意限制)。
有关这些旧 C++03 技术的概述,请参阅我 2010 年的博客文章“3 ways to mix in a generic cloning implementation ”。
关于c++ - 将 unique_ptr 的内容复制到未知派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355456/
我有一个无法理解的奇怪编译问题。 //I know, you should never derive from the STL Library template class SharedClass :
我是一个刚开始学习 Haskell 的菜鸟,所以如果我问愚蠢的问题,请耐心等待。 最近我在 SO 中遇到了演示如何导出函数和表达式的类型和实现的问题(诸如 How can I understand "
如何自动派生此 GADT 的 Read 实例: {-# LANGUAGE GADTs, StandaloneDeriving #-} data TypeDec a where TypeDecInt
我遇到了我想要的情况 Deal class要注意它DealDetail type反之亦然,我想 DealDetail注意Deal type .将来我想有很多 Deal 的后代和 DealDetails
我是 C# 新手,所以请多多包涵。 好的,所以我在不同的程序集中有两个类需要相互引用: namespace AssemblyA { class A { private B MyB {
简而言之,我已经实现了一个派生自 SynchronizationContext 的类,以便 GUI 应用程序可以轻松地使用在 GUI 线程以外的线程上引发的事件。我非常感谢对我的实现的评论。具体来说,
我正在设计一个小型系统,想知道如何为派生类分配内存的细微差别。 如果我有两个类(class) class foo { public: int a; Foo(): a(0) {}; }; class
我正在尝试编写一个派生 PartialEq 的枚举,其中包含一个手动执行此操作的特征对象。我使用了解决方案 here为了强制 Trait 的实现者编写相等方法。这无法编译: trait Trait {
以下代码可以编译(特别是 MyError 被识别为具有调试特性): use std::str; use std::fmt; #[derive(Debug)] enum MyError where F:
是否有一种简单的方法来注释结构中的字段,以便在派生 PartialEq 特征时忽略它们?例如: #[derive(PartialEq,Eq)] pub struct UndirectedGraph {
我正在编写代码来处理“Foo”类型的对象。 foo 是一种容器,为了提供对其元素的高效和抽象访问,它提供了 Element 类型的嵌套类。 Element 包装对象在容器中的位置。 现在,“Foo”可
假设如下: class child : public parent { public: fun1(parent * obj); //somewhere on the child class
我有几个模板类 template class Transition { public: virtual Cost getCost() = 0; }; template class St
我正在尝试使用自定义 QSortFilterProxyModel . 这是我的标题: #include class QSortFilterProxyModel_NumbersLast : publi
我正在使用 C# 和 mvc3。我在解决方案中添加了一个项目。我想创建一个新 Controller 并让它从我添加的项目中的 Controller 派生。我该怎么做? 最佳答案 在 Visual St
我在 python 中有一个对象,它派生自 QtGui.QGraphicsPixmapItem,具有一些基本属性和方法。在对此对象的引用上调用 deepcopy 后,当我尝试使用该副本时收到一条错误消
由于只能给FixedDocument添加页面,所以我写了一个派生类: public class CustomFixedDocument : FixedDocument { public voi
我在自定义 QMainWindow 时遇到了很大的问题,因为我不知道如何实现以下内容: 在 QMainWindow 文档中,QMainWindow 有一些用于工具栏、停靠小部件、状态栏和其他的特殊区域
我想感受一下QT,决定写一个小的十六进制编辑器。为此,我需要一个允许滚动的小部件。经过一番研究,我发现 QTextEdit 为此目的派生自 QAbstractScrollArea。在阅读 QAbstr
我正在寻找一种可以从已经发生的洗牌过程中派生出 key 的算法。 假设我们有被打乱的字符串“Hello”: "hello" -> "loelh" 现在我想从中导出一个 key k,我可以用它来撤销洗牌
我是一名优秀的程序员,十分优秀!