本文介绍了Java中防御性副本的低效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名长期学习 Java 的 C/C++ 程序员.我已经阅读了有关通过访问器方法返回对私有字段的引用来破坏封装的问题.标准的 Java 解决方案似乎是防御性复制——调用复制构造函数或 clone() 来创建字段的副本并返回对副本的引用.我不明白为什么似乎没有人担心制作防御性副本的效率低下.在 C++ 中,访问器只会返回一个指向 const 的指针,从而保护私有成员而不进行复制.为什么 Java 没有对 const 的引用?

I'm a longtime C/C++ programmer who's learning Java. I've read about the problem of breaking encapsulation by having an accessor method that returns a reference to a private field. The standard Java solution seems to be defensive copying - calling the copy constructor or clone() to create a copy of the field and returning a reference to the copy. I don't understand why no one seems concerned about the inefficiency of making a defensive copy. In C++, the accessor would just return a pointer to const, protecting the private member without copying. Why doesn't Java have a reference to const?

推荐答案

问题只能由语言设计者正确回答,但我认为问题在于他们无法弄清楚如何使其作为语言设计的一部分工作.我的回忆(来自我曾经遇到的一些Java 设计原理"文档)是 Gosling 等人最初想要支持 const ...

Questions can only be properly answered by the language designer, but I think that the problem was that they couldn't figure out how to make it work as part of the language design. My recollection (from some "Java design rationale" document that I came across one time) was that Gosling et al originally wanted to support const ...

事实上,尽管 C 和 C++ 都支持 const 作为表达可变性约束的一种方式,但它们都存在允许某些代码破坏"约束的漏洞.(请参阅关于 const-correctness 的维基百科文章.)这可能是困难所在想出一个没有(或不需要)导致 Gosling 等人放弃这个想法的漏洞的 Java 设计.

In fact, though both C and C++ both support const as a way of expressing a mutability constraint, they both also have loopholes that allow some code to "break" the constraint. (See the Wikipedia article on const-correctness.) It could be that it was the difficulty of coming up with a design for Java that didn't have (or need) such loopholes that caused Gosling et al to abandon that idea.

另一方面,Java 中防御性复制的需求并不像您想象的那么大,而且这样做的成本也没有您想象的那么大.当防御性副本的成本很高时,Java 中还有其他选择……比如创建不可修改"的包装对象,或者只支持读取"操作的接口.

The flip-side is that the need for defensive copying in Java is not as great as you might imagine, and that the cost of doing it is not as great as you might imagine. And when the cost of the defensive copy is significant, there are other options in Java ... like creating "unmodifiable" wrapper objects, or interfaces that only support "read" operations.

这篇关于Java中防御性副本的低效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:36