27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

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.

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

13.4 What is <strong>the</strong> difference between deep copy <strong>and</strong> 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 />

pg 76<br />

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

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

a programmer really underst<strong>and</strong>s 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 />

CareerCup.com<br />

2 1 8

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

Saved successfully!

Ooh no, something went wrong!