views:

155

answers:

4

Why are copy constructors unnecessary for immutable objects? Please explain this for me.

+5  A: 

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.

nullptr
+1 there's no point in having two instances of equal immutable objects - just use the same instance everywhere.
Grundlefleck
+1  A: 

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.

Reed Copsey
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
+2  A: 

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.

JaredPar
+1  A: 

it's so natural because value of immutable object can't be changed.

erasmus