Why are copy constructors unnecessary for immutable objects? Please explain this for me.
4 回答
Because the value cannot change, it's every bit as good to reference the same object in all cases, there's no need to have an "extra copy", so to speak.
这是一个依赖于语言的问题,尤其是在生命周期方面。暂时让我们忘记那些。
复制构造函数很有价值,因为它们允许您获取一个对象并创建一个完全独立的副本。这很有价值,因为您现在可以独立于第一个对象修改第二个对象。或者一个组件可以创建一个私有副本来保护自己免受其他组件从其下更改对象的影响。
不可变对象是不可更改的。创建不会更改的对象的副本没有任何价值。
现在让我们再来谈谈生命。在像 C++ 这样的语言中,复制构造函数还允许您解决内存/生命周期问题。例如,如果我正在编写一个需要 a 的 API,SomeType*
并且我希望将其保留比我的方法的生命周期更长的时间。在 C++ 中,最可靠的方法是通过复制构造函数创建对象的副本。
This is somewhat language dependent:
However, many languages require a copy constructor. If you don't provide one, the language will implicitly generate one.
With an immutable object, however, this is typically fine, since the default copy constructor (typically) does a shallow copy of all values. With a mutable data type (ie: containing internal object references to other objects), shallow copying is typically a poor choice, since the copy is only copying the reference/pointer encapsulated within it.
这很自然,因为不可变对象的值无法更改。