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.

13 9 Write a smart pointer (smart_ptr) class<br />

SOLUTION<br />

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

CareerCup com<br />

pg 76<br />

Smart_ptr is <strong>the</strong> same as a normal pointer, but it provides safety via automatic memory It<br />

avoids dangling pointers, memory leaks, allocation failures etc The smart pointer must maintain<br />

a single reference count for all instances<br />

1 template class SmartPointer {<br />

2 public:<br />

3 SmartPointer(T * ptr) {<br />

4 ref = ptr;<br />

5 ref_count = (unsigned*)malloc(sizeof(unsigned));<br />

6 *ref_count = 1;<br />

7 }<br />

8 SmartPointer(SmartPointer & sptr) {<br />

9 ref = sptr.ref;<br />

10 ref_count = sptr.ref_count;<br />

11 ++*ref_count;<br />

12 }<br />

13 SmartPointer & operator=(SmartPointer & sptr) {<br />

14 if (this != &sptr) {<br />

15 ref = sptr.ref;<br />

16 ref_count = sptr.ref_count;<br />

17 ++*ref_count;<br />

18 }<br />

19 return *this;<br />

20 }<br />

21 ~SmartPointer() {<br />

22 --*ref_count;<br />

23 if (*ref_count == 0) {<br />

24 delete ref;<br />

25 free(ref_count);<br />

26 ref = NULL;<br />

27 ref_count = NULL;<br />

28 }<br />

29 }<br />

30 T getValue() { return *ref; }<br />

31 protected:<br />

32 T * ref;<br />

33 unsigned * ref_count;<br />

34 };<br />

2 2 4

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

Saved successfully!

Ooh no, something went wrong!