I want to build a class with functions that may throw exceptions that I want to catch when I use it.
I inherit my_exception from the standard exception class.
I implement the what() function so that it returns a string that is stored in a private string variable
I think it would be better to define the exception as a nested class, the way it's done in iostream library with ios_base::failure.
What I'm less sure about, is where and how I should define the object of my_excpetion. I wish I could see the inner code of the iostream functions and see how they did it.
I have thought about several options:
Short answer: You are going to want to throw the exceptions as objects, rather than as pointers. You will catch them as references.
Longer answer: all of the options you list are valid. In general, the reason you are going to want to throw an object, rather than a pointer, is becuase of the choices you give yourself and your clients when the exception is caught.
If you catch by pointer,
catch (my_exception* e) then you don't know from looking at it whether you should delete the memory or not.
If you catch by value,
catch (my_exception e) then you have a risk of slicing, if the exception object ends up being a base class with some other derived classes.
Catching by reference has neither of these problems. If you write
catch (my_exception& r) then you can catch polymorphic objects, and you don't have to worry about releasing the memory.
So, to answer your other question, when you throw, just throw a temporary object:
throw my_exception(). This creates a temporary object that is (probably) copied when thrown, caught by reference, and destroyed automatically when it goes out of scope at the end of your catch block. (This is actually another benefit of catch-by-reference over catch-by-value, since catch-by-value creates yet another copy when it's caught.)
As for your other, derived exception classes, it's a style choice. Deriving from my_exception with a different what() implementation is pretty standard. I wouldn't say you need to get fancy with storing the strings or instances in static objects - they're small, and constructing one is going to take practically no time compared to the process of unwinding the stack when the exception is thrown.