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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 7 | Object Oriented Design<br />

1 struct Object { … };<br />

2 struct RefCountPtrImpl {<br />

3 int count;<br />

4 Object * object;<br />

5 };<br />

6 struct RefCountPtr {<br />

7 RefCountPtrImpl * pointee;<br />

8 };<br />

Advantages: no memory overhead because of two pointers.<br />

Disadvantages: performance penalty because of extra level of indirection.<br />

3. Intrusive reference counting.<br />

1 struct Object { … };<br />

2 struct ObjectIntrusiveReferenceCounting {<br />

3 Object object;<br />

4 int count;<br />

5 };<br />

6 struct RefCountPtr {<br />

7 ObjectIntrusiveReferenceCounting * pointee;<br />

8 };<br />

Advantages: no previous disadvantages.<br />

Disadvantages: class for intrusive reference counting should be modified.<br />

4. Ownership list reference counting. It is an alternative for approach 1-3. For 1-3 it is only<br />

important to determine that counter is zero—its actual value is not important. This is <strong>the</strong><br />

main idea of approach # 4.<br />

All Smart-Pointers for given objects are stored in doubly-linked lists. The constructor of a<br />

smart pointer adds <strong>the</strong> new node to a list, <strong>and</strong> <strong>the</strong> destructor removes a node from <strong>the</strong> list<br />

<strong>and</strong> checks if <strong>the</strong> list is empty or not. If it is empty, <strong>the</strong> object is deleted.<br />

1 struct Object { };<br />

2 struct ListNode {<br />

3 Object * pointee;<br />

4 ListNode * next;<br />

5 }<br />

CareerCup.com<br />

1 6 8

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

Saved successfully!

Ooh no, something went wrong!