Thursday, April 25, 2013

Dependency walker

Dependency walker is a great program that tells you what dlls your windows program is using. So you can ship your program with only those dlls and not need to carry a number of unnecessary files.

Wednesday, April 24, 2013

SDM - SATA disk module

For last few days I have been working on a SDM based system. The goal was to setup a lightweight system with a SDM instead of a SATA hdd as main storage. The concern was that the SDM is supposed to have write failure protection. This will prevent data corruption in case of power failure.
The SDM was an apacer module and was of 4GB capacity. As I had worked on such small scale systems the task of installation and configuration was handed to me.
The installation was straight forward. We were going to start with a minimal CentOS Desktop and add extra packages as per need. So to safely test it I started with a 4GB virtual machine in VirtualBox.
I installed CentOS in it and that took about 1.6GB of available space. Next I put a minimal QT and QWT library package plus our Client software on top of that. This consumed about 300 MB of more space. Finally I installed PostgreSQL v9.1 as required. This took another 180MB after creating the empty databases etc.
Later I installed telnet, vsftpd and x11vnc servers. And our machine was ready. Configuring so many pieces of software was complex task but I had help from implementation veterans.
After it was all tested fine, we replicated it on DOM.
So after about 3 days of work, our DOM based Client is ready. Later the implementation guys imaged the setup for replicating on multiple machines.
It was good exercise in that I get to know CentOS better and also so much configuration helped me better understand the various parts and pieces of the configuration for the software involved.
Later I performed some database performance and storage profiling for this DOM based system. It was found that with our current data acquisition profile we can comfortably store at least 10 days worth of data on such a system. This added with power failure protection makes it a good solution.

Fixing Turbo C in windows 7

There's a FIXED version of tc floating around in the net and for general programs it works well. But one of my friends being an adventurous soul wanted to try some graphics functions and the program wouldn't run. The error was related to the path to the BGI files.
The problem came to me and I remembered this being caused by the c:\Program Files location of turbo c folder. So I had him copy it to C drive and modify the path accordingly.
With updated path the program stared working and a circle appeared on the screen.
Made me recall my own college days.

Tuesday, April 23, 2013

GPS run/cycling trackers

I have wanted to track my exercise for a long of time. But I don't exercise that much - couple of long walks a week plus some aerobics. So I really was being lazy at it. But I've decided to up my efforts and so I was looking for an app that would help me keep track of my efforts and the amount of distance I passed on and the speeds etc.
After going through the measly no of such apps on my WP Omnia, I stumbled across "run the map". And after using it for a few times I think it's a great app for tracking your exercise.
The main interface is divided into 3 pages - first page shows Recorder i.e. speed, distance and elapsed time. This page also has start-stop button as well as exercise selector. Below these, we get current values for speed and altitude.
Next page is maps which shows your real time path updated at regular intervals.
The last page is mixed mode where you get to see both the map and recorder values.
Also available are features to export GPX or KML files of your runs which you can import on other services and apps for interoperability.
Overall "run the map" is a great exercise map tracker.

Wednesday, April 17, 2013

Tuesday, April 16, 2013

Very interesting discussion

I was searching for a decent way to kill hung jobs and stumbled onto following discussion:
Orig URL:
It's very informative!
A: I tried to kill all my background jobs submit earlier under KUbuntu by
kill -9 $(jobs -p)  
Although this command immediately gave the message like
[1] Killed myjob1
[2] Killed myjob2
I can still see their processes hanging in the output of top and the CPU and memory usages are not changed in the output of uptime and free.
So I guess I must have not killed them properly. Can someone please explain what's happening to me and what shall I do?
I found that in top, if type k and input the PID I can kill the processes one by one. SO is this different from the command kill?
I also found somewhere online about not recommending kill -9
Useless Use of Kill -9 form letter
(Quote abomination)
No no no. Don't use kill -9.
It doesn't give the process a chance to cleanly:
1) shut down socket connections
2) clean up temp files
3) inform its children that it is going away
4) reset its terminal characteristics
and so on and so on and so on.
Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!
Don't use kill -9. Don't bring out the combine harvester just to tidy up the flower pot.
Is this true? What does it mean by "send 15", "send 2" and "send 1"? Are they commands themselves or "kill -15 PID", "kill -2 PID" and "kill -1 PID"?
Thanks and regards!

5 Answers

Your process is probably dead but it still show up in the process table entry because it is a "zombie process". When a child process terminated and completely disappeared (except its process table entry) and the parent wouldnt be able to fetch its termination status (thru any of the wait functions), it is called zombie... Killing (thru signal) a zombie wont work because it is already terminated. What you need to do is find out its parent process and kill thjat one cleany, thus not using kill - 9
here are two simple steps to kill a zombie...
  1. if the parent is still alive, try to kill it (or SIGHUP is all you need)
  2. if number 1 fails, there is a bug in the kernel.... reboot is your friend and fix that bug :->

see man kill for a definition of the various signals available, but yes.
  • 15 is SIGTERM, and asks a program to exit.
  • 2 is SIGINT and is equivalent to Control-C
  • 1 is SIGHUP, and indicates that the terminal has hung up.
These inform a process that the user is "done" with the process, though they indicate somewhat different reasons.SIGTERM might be interpreted as "finish the currrent task, but then exit; don't start another", SIGINT means "abandon what you're doing and quit", SIGHUP just means nobody's listening anymore (a server process might legitimately react to SIGHUP by discontinouing its console output and continuing to run).
  • 9 is SIGKILL, and is special in that it's the only one that the process can't catch and handle internally. It simply results in the kernel never returning control the the process, giving it no chance to clean up.

It does mean using kill -15 PID (or another number) instead of kill -9 PID. The numbers are equivalent to different unix signals.

It means type "kill -1" or "kill -15" instead of typing "kill -9". Kill -9 is a hardcore bullet in the head of any running process, kills it dead in a dirty state which can cause memory leaking, blah blah.
If you're typing kill -9 and it's not working, then I'd look to make sure the process is not getting respawned, and that you have permission to kill that process.

Signal 9 is SIGKILL. Sending a SIGKILL is asking the OS to immediately kill the process, no questions asked. The process is not notified in advance and has no chance to clean up after itself.
Signal 15 is SIGTERM. Sending a SIGTERM is asking the OS to ask the process to shut itself down.
SIGKILL may be ignored if the OS thinks the process is doing IO, or if it's a Zombie (A child process whose parent didn't clean up after it).
SIGTERM may be ignored by the application, but it is not recommended that applications do this, as OSes send SIGTERM during shutdown, followed shortly by SIGKILL if a program is still running.
Note: The command line kill is always asking the OS to send a signal to the application, which it may or may not do based on who owns the process, etc...

Ultimately I have decided to create a shell block for safely killing any process but it's going to be a big task. Below is what I am working on right now.

killall myprocess
MYPROCCOUNT=`ps -e | grep myprocess | wc -l`

while [ $MYPROCCOUNT -gt 0 ]; do
       MYPROC=`ps -e| grep myprocess| tail -1| xargs |cut -d" " -f1`

       if [ -z $MYPROC ]; then
           echo "All myproc's killed!"
            echo "Killing $MYPROC"
            `kill -9 $MYPROC`

       MYPROCCOUNT=`ps -e | grep myprocess | wc -l`

I'll have to add lot more code to handle 15, 2 and 1 signals and then give 9 as ultimate kill!

Wednesday, April 10, 2013

One line of code made so much change!


Monday, April 8, 2013

Image Processing

If you are familiar with image processing textbooks and articles, you must have seen the following picture:
Following is an extract from the comp.compression FAQ:
For the curious: 'lena' or 'lenna' is a digitized Playboy centerfold, from November 1972. (Lenna is the spelling in Playboy, Lena is the Swedish spelling of the name.) Lena Soderberg (ne Sjooblom) was last reported living in her native Sweden, happily married with three kids and a job with the state liquor monopoly. In 1988, she was interviewed by some Swedish computer related publication, and she was pleasantly amused by what had happened to her picture. That was the first she knew of the use of that picture in the computer business. 

A scan of the original Lenna from Playboy is available from:
The editorial in the January 1992 issue of Optical Engineering (v. 31 no. 1) details how Playboy has finally caught on to the fact that their copyright on Lena Sjooblom's photo is being widely infringed. However Wired mentionned that: "Although Playboy is notorious for cracking down on illegal uses of its images, it has decided to overlook the widespread distribution of this particular centerfold".
The following was found on sci.image.processing:

Subject: Lena (parting words) (longish)
Date: 21 Feb 1996 13:33:20 GMT
Newsgroups: sci.image.processing

If Dr. Munson and the Transactions can forgive the copyright infringment, the departing Editor-in-chief's comments on the Lena deal are too good not to share with the group.

A Note on Lena

During my term as Editor-in-Chief, I was approached a number of times with the suggestion that the IEEE TRANSACTIONS ON IMAGE PROCESSING should consider banning the use of the image of Lena. For those of you who are uninitiated in this brouhaha, let me provide a few facts. The original Lena image was a photograph of a Swedish woman named Lena Sjooblom, which appeared in the November 1972 issue of Playboy Magazine. (In English, Lena is sometimes spelled Lenna, to encourage proper pronunciation.) The image was later digitized at the University of Southern California as one of many possible images for use by the research community. I think it is safe to assume that the Lena image became a standard in our "industry" for two reasons. First, the image contains a nice mixture of detail, flat regions, shading, and texture that do a good job of testing various image processing algorithms. It is a good test image! Second, the Lena image is a picture of an attractive woman. It is not surprising that the (mostly male) image processing research community gravitated toward an image that they found attractive. The Woody Allen buffs among you may be interested to know that the Lena image appeared in the movie Sleeper. Tom Huang pointed this out to me. In the scene where Allen awakes in the year 2173, he is asked to identify a number of artifacts from the past, including photographs of Joseph Stalin and Charles de Gaulle, and the issue of Playboy Magazine containing Lena. The view to the movie watcher is fleeting and somewhat unclear, but this is the closest I have come to viewing the original image. From second-hand reports from Sweden, I am told that Lena is living in a small town south of Stockholm. She is said to be quite amazed that her image has become a standard in the research community. In recent years, Playboy Enterprises was giving thought to enforcing their copyright on the Lena image (see Brian Thompson's editorial in the January 1992 issue of Optical Engineering). It appears, though, that this is no longer the case.

So what is the problem? Well, quite understandably, some members of our community are unhappy with the source of the Lena image. I am sympathetic to their argument, which states that we should not use material from any publication that is seen (by some) as being degrading to women. I must tell you, though, that within any single segment of our community (e.g., men, women, feminists), there is a complete diversity of opinion on the Lena issue. You may be surprised to know that most persons who have approached me on this issue are male. On the other hand, some informal polling on my part suggests that most males are not even aware of the origin of the Lena image! I have heard feminists argue that the image should be retired. However, I just recently corresponded with a feminist who had a different point of view. She was familiar with the Lena image, but she had not imagined that there could be any controversy. When I offered an explanation of why some persons are offended by the use of the image. she responded tartly. A watered-down version of her reply is, "There isn't much of Lena showing in the Lena image. This political correctness stuff infuriates me!"

So there you have it. Much of our community is blind to the fact (until now!) that there is a controversy. Among those who are "tuned in," there is vigorous disagreement. As Editor-in-Chief, I did not feel that this issue warranted the imposition of censorship, which, in my view, should be applied in only the most extreme circumstances. In addition, in establishing the precedent, I was not sure where this might lead. Should we ban the Cheerleader video sequence? Should we establish an oversight panel to rule on acceptable imagery? Instead, I opted to wait and see how the situation might develop. I suspected that the use of Lena would decline naturally. as diverse imagery became more widely available and as the field of image processing broadened in scope. Although the use of Lena has declined (witness our January, 1992 issue!), this image still appears so frequently that I imagine it must be grating on those who oppose its use. What to do? I favor a compromise of sons. I suggest that the IP authorship be more sensitive to the feelings of those who are offended by the Lena image. In cases where another image will serve your purpose equally well, why not use that other image? After all, why needlessly upset colleagues? And who knows? We may even devise image compression schemes that work well across a broader class of images, instead of being tuned to Lena!

Editor-in-Chief, Emeritus

I was gratified to note that there were at least three articles in that issue of Tr. Img Proc. with Lena test image! There was also more using The Photographer, maybe we should start a legend that the Photographer was photographing Lena at the Bridge............ ;')
The following was found on Wired
Playmate Meets Geeks Who Made Her a Net Star
by Janelle Brown
6:11pm 20.May.97.PDT

Having graced the desktops of millions of engineers, researchers, and digital imaging specialists for 25 years, Playboy's Miss November 1972 - dubbed the "First Lady of the Internet" - is coming to meet her fans.

Lena Sjooblom became Net royalty when her centerfold was scanned in by programmers at the University of Southern California to use as a test image for digital compression and transmission over Arpanet, the precursor to the Internet. Years later, the "Lena" image (a closeup of her face and bare shoulder) is till in the industry standard for tests. This week, Sjooblom is making her first public appearance at the 50th Annual Conference of the Society for Imaging Science in Technology, as part of an overview of the history of digital imaging.

"They must be so tired of me... looking at the same picture for all these years! comments Sjooblom, who was, until last November, unaware of her fame, and who has still never seen the Net. This week, she is busy signing autographs, posing for pictures, and giving a presentation about herself at the conference.

Playboy helped track down the Swedish native in Stockholm, where she helps handicapped people work on (non-networked) computers. Although Playboy is notorious for cracking down on illegal uses of its images, it has decided to overlook the widespread distribution of this particular centerfold.

Says Eileen Kent, VP of new media at Playboy: "We decided we should exploit this, because it is a phenomenon."

Practical C++ Error Handling in Hybrid Environments

Exception-safe code is notoriously difficult to get right in C++. Still, it is the recommended way to go, at least according to C++ gurus. And for a reason. If you write nontrivial programs or libraries in C++, you should probably study exception handling and use it where appropriate.
In the real world, however, exception handling is not always possible, viable, or used by anyone. So what do you do if you need to integrate or interoperate with software that doesn't use exception handling? In this article, I discuss situations where exception handling is not used and why. I then demonstrate how to interface your exception-handling code to other software components that practice a different error-handling method.

Error-Handling Strategies in C++

There are different ways to report and handle errors in C/C++. (You have to consider C because C++ is—more or less—a superset of C and often C++ programs link against C libraries, libraries that expose C APIs, call C code, and are called from C code via global/static functions or function pointers.)
Exceptions are the official error-handling mechanism, of course. However, C++ was initially designed without exceptions and it shows. For example, IO streams don't throw exceptions by default, but set a "fail" bit when something goes wrong. Compilers, being backward-compatible creatures, usually provide switches to turn exception handling on/off. This means that if you call new and run out of memory, you either get a NULL pointer or an std::bad_alloc exception.
Status/Return codes are another error-handling technique. This is as simple as it gets and provides the lowest common denominator that is always available, even if you port your code to different languages. Status/Return codes foster visibility in the source code of the path of specific errors but at the price of clutter.
setjmp/longjmp is an early C language stack-unwinding exception handler that is widely used to handle input errors detected by deeply nested function calls, such as the recursive descent parsing algorithms of source code language translators. Like C++ exception handling, setjmp/longjmp eliminates the need to know about and handle error return codes all the way up the recursive ascent. Unlike the C++ try/catch mechanism, which has to destroy automatic objects along the way up, setjmp/longjmp adds very little runtime and space overhead to a program.
Likewise, errno is yet another C error mechanism. It is just a global object that can contain an error code. It is not thread-safe so its raw usage is discouraged in concurrent systems.

Managed Environments/Proprietary Error-Handling Mechanisms

Because Microsoft is the only vendor that provides deep integration to operating system facilities (SEH) or managed environments (COM and CLR) at the C++ level, all of the following mechanisms are Windows specific. This is an important trend. The Mono runtime brings .NET to the cross-platform world, and while it doesn't yet provide a C++ front-end, there is work towards it. All of these error-handling mechanisms integrate and interoperate with each other and with C++ exceptions to some degree.
Get/Set LastError is a glorified errno for Win32. It's better than errno in the sense that code in other languages can access it through the Windows API. Cross-language, as opposed to cross-platform, code is a big concern of Microsoft.
Win32 Structured Exception Handling (SEH) is the low-level OS mechanism that calls a certain callback when some thread faults. The Visual C++ compiler wraps it for you and implements the C++ exception model on top of it. You can ignore it most of the time, just know that it's there in the bizarre case you need to dig that deep and find out something.
COM/ATL error handling is a different beast. COM was designed to be language agnostic. As such it couldn't rely on any language's error-handling facilities. So, COM came up with its own error-handling facility. COM has an error object that is accessible via various COM interfaces: ICreateErrorInfo for creating error objects, IErrorInfo for accessing error information, and ISupportErrorInfo to check if a certain COM class actually creates instances of the error object. The punch-line is that I don't really know how ubiquitous the COM error object is. When I used COM/ATL a lot, I used plain HRESULTs, which is equivalent to C status/return codes.
In terms of managed (.NET/CLR) exceptions, the .NET/CLR assimilates, subsumes, and encapsulates all other Windows technologies. It provides its own exception model and specific CLR extensions for C++, but also has a unique mechanism for interfacing with pure C++ code. It reportedly just works most of the time. I've never used it.

When Exceptions Are Not Used (And Why)

There are two metareasons for not using C++ exception handling:

  • You can't. This includes C code (or code that's exposed through a C API), code that runs in some managed environment, and legacy systems built using a compiler that doesn't support exceptions properly or not in a cross-platform way.
  • You don't want to (or the powers that be don't want to). This includes performance-critical systems where you don't want to pay the overhead of exceptions. It also includes uncomfortable developers who don't want to mess with exceptions in the first place, or the desire to have a single error-handling mechanism across the system.
C++ is the only language I'm aware of that even lets you turn exception handling on/off. In other languages, you either have exceptions or you don't. You can use other mechanisms if you want, but exceptions are there and runtime failures probably trigger exceptions, so you must be ready to catch them.
If you develop code that you want other people to use, you would be wise to consider exposing it through a C API. The C++ Application Binary Interface (ABI) is not part of the C++ Standard. Every compiler vendor changes it with every major version (and sometimes more often). The result is that you can't statically link a C++ library if it was compiled using a different compiler. It is also not possible on a nonWindows platform to load C++ classes directly from a dynamic library. So, if you are not in the business of shipping source distributions and you want to reach a larger audience than people who happen to have exactly your compiler, stick to C.
With managed environments, you don't even have the choice. If your code must run in a managed environment, you must play by its rules. There isn't much point in throwing an uncaught exception in your COM out of a process module. It would never make it across to the calling code without marshalling.
Legacy systems can be big, yet fragile, creatures. The smallest change might break them, they may rely on undocumented APIs or bugs in a specific compiler implementation. Upgrading the compiler or changing the error-handling strategy is typically prohibitively expansive. Chances are you won't be able to persuade the powers that be to upgrade the compiler and potentially destabilize the system just so you can use cool C++ exceptions in your shiny new module.
Exception handling has a runtime overhead, even when exceptions are not thrown. The compiler needs to manage a list of all the stack objects that were constructed to call their destructors when an exception is thrown. This implies at least a space overhead (if the list is prepared during compilation). If the preparation of this list is done at runtime, then there is also a time overhead. Many performance-critical systems have a shoestring budget for CPU cycles and memory bits, and developers can't afford the cost of exception handling.
In general, C++ developers, who are considered hard-core in comparison to other developer, are uncomfortable with C++ exception handling due to the complexity of implementing it correctly. Exception handling in other languages that support garbage collection (Java, Python, C#) is much simpler and developers have no problem using it.. Still, exceptions have a lot going for them. They can considerably simplify error handling in C++ programs. However, they are not simple by themselves. Many developers just know that getting C++ exceptions to work is complicated. Many experienced C++ developers never used exceptions in their code because they only worked on projects that fall under the aforementioned restrictions or they learned C++ before exceptions were introduced to the language. In the initial meeting of a new project when it's time to pick an error-handling strategy, inexperienced developers tend to stick to what they know. Exception handling is not as cool as templates, so developers often don't feel that they "have" to use it, just because they never used it before.
Software is complicated. When system architects face crucial decisions such as picking an error-handling strategy, they often prefer a single mechanism instead of two that have to interact. Since many libraries and existing code bases don't leverage exceptions, this single mechanism is often a simple return code, or one of the other nonexceptional mechanisms.

Exception Handling in Hybrid Environments

Error handling is hard. Mixing multiple mechanisms is harder. The only thing that's even harder is explaining why your system doesn't handle errors properly. Different situations call for different solutions.
Sometimes avoiding exceptions is the right thing to do. Here are a few factors in favor of this approach:

  • You maintain an existing system that doesn't use exceptions.
  • The piece you work on is performance critical (pending profiling).
  • Team members are not familiar with exception handling and are not keen on learning.
If you have already made the decision to use exceptions, you can pick and choose your battles. Not every function must throw exceptions and you probably don't want to convert the error-handling style of a large existing code base. Use exception handling in new code and where it makes sense. For example, if there is a complex piece of existing code that's buggy and tends to mismanage resources when errors occur, it is probably a good candidate for conversion. There is a good chance that the design is not optimal to begin with so while you refactor it, you can also convert it to use exception handling. You would be surprised how small the code can get with automatic objects managing cleanup of resources in destructors.
Catch exceptions on the interoperability border. When you need to interface with another component, you must conform to its API of course (unless you define that API, then the other party has to conform). If this API involves returning error codes or setting errno or any other error-handling reporting mechanism, you must not leak unhandled exceptions. It doesn't mean that you can't use exceptions in this case. It just means that you should catch your own exceptions internally in each API method/function and map your exceptions to the appropriate API convention.
The reverse is also true. If your code is heavily exception oriented and you call into some nonexception API, you don't have to deal with yet another error mechanism. You can wrap all the calls through this API in an object that converts API error codes to exceptions.


StreamingException (Listing One) is an exception class that exposes a stream interface and allows one-line formatting of complex error messages. The design and implementation are interesting and use C++ constructs such as std::auto_ptr, the mutable modifier, and (begrudgingly) exception specifications.

class StreamingException : public std::runtime_error
StreamingException() :
      (new std::stringstream()))
~StreamingException() throw()
StreamingException & operator << (const T & t)
  (*ss_) << t;
  return *this;
virtual const char * what() const throw()
  s_ = ss_->str();
  return s_.c_str();
mutable std::auto_ptr ss_;
mutable std::string s_;
Listing One
StreamingException is derived from std::runtime_error. It's good form to derive your exception classes from std::standard_error because it communicates your intention (I hope you throw your exceptions at runtime) and it lets the application catch runtime errors from multiple sources (as long as all the other sources follow this guideline, too). In addition, std::runtime_error provides the what() method that returns a text message with the error description. By default, what() returns the message that was passed in the constructor. StreamingException overrides the virtual what() and returns instead the contents of its stream (it's not called "StreamingException" for nothing). The StreamingException constructor takes no arguments and passes an empty message to its base std::runtime_error constructor (remember that this message is not used anyway). The constructor then creates a stringstream instance on the heap and puts it in a mutable std::auto_ptr. If you studied your smart pointers well, you know that std::auto_ptr has the unusual property of ownership transfer. When you assign it to another auto_ptr, the assignee gets the ownership of the pointed object and the original object is left with nothing. This peculiar behavior is sometimes dangerous and often gets in the way (you can't put auto_ptr into a standard container because you will lose the ownership to the container). In this case it is exactly what the doctor ordered. You will soon see why and why it must be mutable.
The destructor is quite empty, but it can't be dropped. The compiler will indeed generate a default destructor for you, but the default destructor doesn't come with an empty throw() exception specification. This is required because std::runtime_error defines such a virtual destructor. Exception specifications are an annoying misfeature of C++ that specifies what exceptions a method may throw and are part of the method signature. Thankfully, they are optional so you don't see them a lot in the wild.
The templated operator<< is where the pedal hits the metal. This is a template method that accepts any streamable T. That translates to standard types plus any other type that implements a conforming operator<<. The implementation simply streams the T argument to its member stringstream s_. The return value is a reference to the StreamingException class itself. This allows chaining multiple calls to operator<<.
Finally, StreamingException overrides the virtual what() method to return the contents of its stringstream. Note the exception specification again.
Example 1 is straightforward. It tries to compare 5 to 3 and throws a StreamingException when the comparison fails. Note the dynamic message was constructed in one line and streamed into the exception while throwing it! (And yes, it works.)

int main (int argc, char * const argv[])
   if (5 != 3)
     throw StreamingException() << 5 << " is not equal to " << 3;
 catch (const StreamingException & e)
   cout << e.what() << endl;
 return 0;

Example 1: Using StreamException.
In the catch clause the exception is caught by a const reference. This is a good practice, too. Please refer to your favorite C++ book for the reasoning. The catch clause proceeds to print the exception's message via what() to the standard output.
It's time to reveal StreamingException's secrets. The thrown exception is a temporary object. The instance that is caught in the catch clause is actually a copy of the original exception. I had a couple of choices to keep the error message intact during this copy. Most of them involved implementing a copy constructor and some of them involved duplication of the error message. Instead, I opted to use auto_ptr, which takes care of two issues: It deletes the dynamically allocated stringstream on destruction and it transfers the ownership when StreamingException is copied. Okay, so why mutable? Well, the caught exception is a const reference because the catching code is not supposed to modify the internal state of the exception. However, auto_ptr with its ownership transfer semantics does require a change of state. The mutable modifier was invented exactly for this purpose—being able to modify the internal state of an object while preserving its conceptual constness.


C++ is a multiparadigm programming language supporting procedural, object-oriented, generic, and even metaprogramming. C++ also allows multiple error handling strategies to coexist in the same system. Getting it right is not a simple task. Still, it is possible to create complicated error messages in a safe and concise manner.