Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
This article describes an architectural problem and then compares two solutions, using the C++98 and C++11 standards respectively.
Suppose you have a class called 'Test' you want to have managed. So, a class called 'Source' is written for simply this purpose. It is kind of a source, because it produces read-only versions of the Test managed by it. These read-only Tests are used by Observer.
An example where one would want to do this, is when a program loads its parameters from file. These parameters are not to be altered, but might be used throughout the program.
But the problem is as follows: what if the original source changes the thing its manages? How can the observer know this?
The code below compiles, runs but does not meet our needs:
#include <cassert> |
The final line of code shows the problem: the observer still has an old copy of Test (with a value of one), instead of the new one (with a value of two).
When instead of the observer having a boost::shared_ptr<const Test>, this is changed to boost::weak_ptr<const Test>, the program will give a fine run-time error:
#include <cassert> |
Sure, a run-time error has its drawbacks, but with a debugger its source can be located easily.
When replacing boost::shared_ptr and boost::weak_ptr to std::shared_ptr and std::weak_ptr respectively also gives a fine run-time error:
///The solution: std::weak_ptr |
The problem is, that in this case, a segmentation fault is given, instead of a failed assertion. Also, the debugger could not get me to pinpoint to the source of the error.
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.