Why are copy constructors unnecessary for immutable objects? Please explain this for me.
-
Possible duplicate of [What makes immutable objects to be published without safe publication techniques?](http://stackoverflow.com/questions/17000617/what-makes-immutable-objects-to-be-published-without-safe-publication-techniques) – Dec 11 '15 at 20:31
4 Answers
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.

- 13,619
- 3
- 34
- 34
-
1+1 there's no point in having two instances of equal immutable objects - just use the same instance everywhere. – Grundlefleck Mar 11 '10 at 18:16
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.

- 733,204
- 149
- 1,241
- 1,454
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.

- 554,122
- 78
- 1,158
- 1,373
-
Copying immutable objects is not optimal - it unnecessarily uses extra resources. This may or may not cause a problem depending on the situation, but copying immutable objects should be discouraged in general. – Grundlefleck Mar 11 '10 at 19:09