c ++ - 克隆对象的最佳方式 [英] c++ - Best way to clone objects

查看:189
本文介绍了c ++ - 克隆对象的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,其实例将负责产生给定类型的新对象。

I have a class whose instances will be in charge of spawning new objects of a given type. Something along the lines:

Spawner::Spawner(const SpawnableObj& obj)
{
    objectToSpawn = obj.clone();
}
SpawnableObj Spawner::spawnNew()
{
    return objectToSpawn.clone();
}

现在我关心的是spawnNew SpawnableObj,所以我的clone()函数只返回它的类型的默认构造的对象。
然而,我可能希望实际返回存储对象的克隆,所以我想知道是否有一种克隆对象,而不进行手动深拷贝的方法?

For now all I care about is spawnNew() returning a default instance of any SpawnableObj, so my clone() function just returns a default constructed object of it's type. I might however want to actually return clones of the stored object in the future, so I was wondering if there's a way to clone objects without doing a manual deep copy?

考虑到我从一个不实现clone()函数的外部类派生SpawnableObject(实际上它隐藏了拷贝构造函数和赋值),所以如果外部基类改变克隆可能不再完成。

This is a larger issue considering I'm deriving SpawnableObject from an external class which doesn't implement a clone() function (in fact it hides away copy constructor and assign), so if the external base class changes the clone might no longer be complete.

编辑:稍有歧义的措辞...有效的问题:
有一种方法来实现clone(),使得基类中的更改不需要更改要在每个派生类中更改的clone()函数(同时仍然不依赖于对象的不安全的浅拷贝),或者

Slightly ambiguous wording... The questions is effectively: Is there a way to implement clone() such that changes in the base class don't require changing the clone() function to be changed in each of the derived classes (while still not relying on an unsafe shallow copy of the object), or at least minimize the changes required.

推荐答案

您将无法正确实施 clone

You will not be able to properly implement clone without implementing copy ctor.

因此,建议先实现复制构造函数。

So, recommend first implement copy-constructor.

可以实现 clone as:

Spawner * Spawner::clone() const {
  return new Spawner(*this);  // <<== this needs copy-ctor implemented
}

您还想查看:什么是复制和交换惯用语? / a>

As bonus you also want to check out: What is the copy-and-swap idiom? too

这篇关于c ++ - 克隆对象的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆