将对象的副本传递给方法-复制的对象是谁? [英] Passing copy of object to method -- who does the copying?

查看:62
本文介绍了将对象的副本传递给方法-复制的对象是谁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在方法调用中传递的对象.假设我使用的语言仅允许您通过引用传递对象,例如Java或PHP.如果该方法对对象进行了更改,它将影响调用方.我不希望这种情况发生.因此,似乎需要复制该对象.

I have an object that I'm passing in a method call. Say I'm using a language that only allows you to pass objects by reference, like Java or PHP. If the method makes changes to the object, it will affect the caller. I don't want this to happen. So it seems like I need to make a copy of the object.

我的问题是:克隆对象是谁的责任?调用者,在调用该方法之前?还是被呼叫者,在它更改对象之前?

My question is: whose responsibility is it to clone the object? The caller, before it calls the method? Or the callee, before it changes the object?

为澄清起见,我希望此方法成为此方法合同的一部分-永远不要修改原始对象.因此,似乎应该取决于制作副本的方法.但是随后,调用者就无法免受无法正确执行此操作的方法的保护.我想这是可以接受的-唯一的替代方法似乎是将其内置到语言中.

Just to clarify, I want this to be part of the contract of this method -- that it never modifies the original object. So it seems like it should be up to the method to make the copy. But then the caller has no protection from a method that doesn't do this properly. I guess that's acceptable -- the only other alternative seems to be to have this built into the language.

推荐答案

通常,如果调用者担心更改,则应复制该副本.如果调用者不在乎,则如果需要执行某些它不应该保留的操作,则该方法应进行复制.

Generally, the caller should make the copy if it is concerned about changes. If the caller doesn't care, the method should make the copy if it needs to do something that it knows shouldn't persist.

这篇关于将对象的副本传递给方法-复制的对象是谁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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