Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are copy constructors unnecessary for immutable objects?

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

like image 460
Jothi Avatar asked Mar 11 '10 18:03

Jothi


2 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.

like image 180
Derek Slager Avatar answered Nov 16 '22 05:11

Derek Slager


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.

like image 4
JaredPar Avatar answered Nov 16 '22 04:11

JaredPar