25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solutions to Chapter 13 | C++<br />

13 4 What is <strong>the</strong> difference between deep copy and shallow copy? Explain how you would<br />

use each<br />

SOLUTION<br />

1 struct Test {<br />

2 char * ptr;<br />

3 };<br />

4 void shallow_copy(Test & src, Test & dest) {<br />

5 dest.ptr = src.ptr;<br />

6 }<br />

7 void deep_copy(Test & src, Test & dest) {<br />

8 dest.ptr = malloc(strlen(src.ptr) + 1);<br />

9 memcpy(dest.ptr, src.ptr);<br />

10 }<br />

CareerCup com<br />

pg 76<br />

Note that shallow_copy may cause a lot of programming run-time errors, especially with <strong>the</strong><br />

creation and deletion of objects Shallow copy should be used very carefully and only when<br />

a programmer really understands what he wants to do In most cases shallow copy is used<br />

when <strong>the</strong>re is a need to pass information about a complex structure without actual duplication<br />

of data (e g , call by reference) One must also be careful with destruction of shallow<br />

copy<br />

In real life, shallow copy is rarely used There is an important programming concept called<br />

“smart pointer” that, in some sense, is an enhancement of <strong>the</strong> shallow copy concept<br />

Deep copy should be used in most cases, especially when <strong>the</strong> size of <strong>the</strong> copied structure is<br />

small<br />

2 1 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!