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 7 | Object Oriented Design<br />

7 10 Describe <strong>the</strong> data structures and algorithms that you would use to implement a garbage<br />

collector in C++<br />

SOLUTION<br />

1 6 7<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts and Algorithms<br />

pg 62<br />

In C++, garbage collection with reference counting is almost always implemented with<br />

smart pointers, which perform reference counting The main reason for using smart pointers<br />

over raw ordinary pointers is <strong>the</strong> conceptual simplicity of implementation and usage<br />

With smart pointers, everything related to garbage collection is performed behind <strong>the</strong><br />

scenes - typically in constructors / destructors / assignment operator / explicit object management<br />

functions<br />

There are two types of functions, both of which are very simple:<br />

1 RefCountPointer::type1() {<br />

2 /* implementation depends on reference counting organisation.<br />

3 * There can also be no ref. counter at all (see approach #4) */<br />

4 incrementRefCounter(); }<br />

5<br />

6 RefCountPointer::type2() {<br />

7 /* Implementation depends on reference counting organisation.<br />

8 * There can also be no ref. counter at all (see approach #4). */<br />

9 decrementRefCounter();<br />

10 if (referenceCounterIsZero()) {<br />

11 destructObject();<br />

12 }<br />

13 }<br />

There are several approaches for reference counting implementation in C++:<br />

1 Simple reference counting<br />

1 struct Object { };<br />

2 struct RefCount {<br />

3 int count;<br />

4 };<br />

5 struct RefCountPtr {<br />

6 Object * pointee;<br />

7 RefCount * refCount;<br />

8 };<br />

Advantages: performance<br />

Disadvantages: memory overhead because of two pointers<br />

2 Alternative reference counting

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

Saved successfully!

Ooh no, something went wrong!