Why a开发者_StackOverflow中文版re copy constructors unnecessary for immutable objects? Please explain this for me.
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.
This is a language dependent question especially with respect to lifetime. For a moment lets forget about those.
Copy constructors are valuable in that they allow for you to take one object and create a completely independent copy of it. This is valuable in that you can now modify the second object independent of the first. Or a component can create a private copy to protect itself from other components changing the object out from under it.
Immutable objects are unchangeable. There is no value in creating a copy of an object that won't change.
Now lets thing about lifetime again. In languages like C++ copy constructors also allow you to work around memory / lifetime issues. For example if I'm writing an API which takes a SomeType*
and I want to keep it around longer than the lifetime of my method. In C++ the most reliable way to do this is to create a copy of the object via a copy constructor.
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.
it's so natural because value of immutable object can't be changed.
精彩评论