Tuesday, September 13, 2011

Weak Pointers

Recently, I was looking at using weak pointers for a project. I have the following code to test locking a shared_ptr via a weak_ptr, both when the shared_ptr is in scope and when it gets out of scope. Initial attempts at using it failed due to a compiler issue.

1:  #include <iostream>
2: #include <boost/make_shared.hpp>
3:
4: using namespace boost;
5: using namespace std;
6:
7: int main()
8: {
9: weak_ptr<int> q;
10: {
11: shared_ptr<int> p = make_shared<int>(9);
12: q = p;
13: }
14: shared_ptr<int> r = q.lock();
15: if (r)
16: cout << "r = " << *r << endl;
17:
18: return 0;
19: }

The Intel compiler issued an error: incomplete type is not allowed; VS compiler along the same lines. It was a header problem; and indeed it was.
This is strange at first though as make_shared includes declaration to shared_ptr class which in turn uses weak_ptr. But WTH, if a type is incomplete it is not declared; inclusion of the proper headers solve the problem.
3:  #include <boost/weak_ptr.hpp>  
Going back to the code, the use of a block after creation of q (line 10, 13) causes p to get out of scope before attempting to lock a shared_ptr, causing an empty r; on the other hand, commenting out the block validates q.lock(), increments p's reference count, and causes the program to display the value of r. These behaviors are expected.