Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why lazy copy when we have deep copy and shallow copy?

Tags:

c++

We have shallow copy and deep copy who can do the job for us when we want to copy objects in C++. So,
What is Lazy copy?
Is this a thing that is taken care by a programmer or compiler does this on its own?
What are the programming scenarios where a lazy copy is advantageous?

like image 204
Vinod Akkepalli Avatar asked Feb 22 '23 18:02

Vinod Akkepalli


1 Answers

What is Lazy Copy?

Wikipedia Defines this aptly.

A lazy copy is a combination of both shallow copy and Deep Copy. When initially copying an object, a (fast) shallow copy is used. A counter is also used to track how many objects share the data. When the program wants to modify an object, it can determine if the data is shared (by examining the counter) and can do a deep copy if necessary. Lazy copy looks to the outside just as a deep copy but takes advantage of the speed of a shallow copy whenever possible. The downside are rather high but constant base costs because of the counter. Also, in certain situations, circular references can also cause problems.

Is this a thing that is taken care by a programmer or something that the compiler does on its own?

The programmer has to implement this behavior for his own classes.
A compiler performs shallow copies in copying functions(copy constructor & assignment operator) by default.
Deep Copy is what a programmer has to implement for his class, so that the special handling of members(pointers) can be in place for copying functions.

What are the programming scenarios where a lazy copy is advantageous?

Ideally,
A situation wherein copying an object causes a performance penalty but the objects are not being modified very frequently the Lazy copy would be advantageous in terms of performance.

The Wikipedia cites a number of examples where, Lazy Copy(Copy On Write) is used.

like image 93
Alok Save Avatar answered Mar 05 '23 12:03

Alok Save