复制构造函数有什么问题?为什么要使用Cloneable接口? [英] What's wrong with Copy Constructors? Why use Cloneable interface?

查看:121
本文介绍了复制构造函数有什么问题?为什么要使用Cloneable接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对C ++进行编程时,我们曾在需要时创建拷贝构造函数(因此我们被教导).几年前切换到Java时,我注意到现在正在使用Cloneable接口. C#遵循相同的路线定义了ICloneable接口.在我看来,克隆是OOP定义的一部分.但是我想知道,为什么要创建这些接口,并且复制构造函数似乎已被删除?

When programming C++ we used to create copy constructors when needed (or so we were taught). When switching to Java a few years ago, I noticed that the Cloneable interface is now being used instead. C# followed the same route defining the ICloneable interface. It seems to me that cloning is part of the definition of OOP. But I wonder, why were these interfaces created, and the copy constructor seems to have been dropped?

当我想到这一点时,我想到如果需要复制其类型未知的对象(例如引用基本类型)的副本,则复制构造函数将无用.这似乎合乎逻辑.但是我想知道是否还有其他我不知道的原因,为什么Cloneable接口比复制构造函数更受青睐?

When I thought about it, I came to the thought that a copy constructor would not be useful if one needs to make a copy of an object whose type is not known (as in having a reference to a base type). This seems logical. But I wonder whether there are other reasons that I do not know of, for which the Cloneable interfaces have been favored over copy constructors?

推荐答案

我认为这是因为在Java和C#中对于引用类型并不需要内在的复制构造函数.在C ++中,对象被命名.例如,从函数返回时,您可以(并且经常)将它们复制(并以C ++ 1x移动),因为返回指针要求您分配动态内存,这将使管理工作缓慢且痛苦.语法为T(x),因此使构造函数采用T引用是有意义的. C ++无法创建克隆函数,因为这将需要再次按值返回对象(并因此返回另一个副本).

I think it's because there is no such inherent need for a copy constructor in Java and in C# for reference types. In C++ objects are named. You can (and you will most often) copy (and in C++1x move) them around e.g when returning from functions, since returning pointers require you to allocate dynamic memory which would be slow and painful to manage. The syntax is T(x) so it makes sense to make a constructor taking a T reference. C++ couldn't make a clone function, since that would require returning an object by value again (and thus another copy).

但是在Java中,对象是未命名的.只有对它们的引用可以复制,但是对象本身不被复制.对于实际需要复制它们的情况,可以使用clone调用(但我在其他anwers中读到的克隆有缺陷.我不是Java程序员,所以我无法对此发表评论).因为不是返回对象本身,而是返回对它的引用,所以克隆函数就足够了.克隆函数也可以被覆盖.这不适用于复制构造函数.顺便说一句,在C ++中,当您需要复制一个多态对象时,也需要一个clone函数.它有一个名称,即所谓的虚拟副本构造函数.

But in Java, objects are unnamed. There are only references to them, which can be copied, but the object itself isn't copied. For the cases when you actually need to copy them, you can use the clone call (but i read in other anwers clone is flawed. i'm no java programmer so i cannot comment that). Since not the object itself is returned, but rather a reference to it, a clone function will suffice. Also a clone function can be overriden. That's not going to work with copy constructors. And incidentally, in C++ when you need to copy a polymorphic object, a clone function is required too. It's got a name, the so-called virtual copy constructor.

这篇关于复制构造函数有什么问题?为什么要使用Cloneable接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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