Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

36.4 Caveat

Note that the solution suggested here has a pitfall.

The manipulator takes the format specification and stores it. The inserter retrieves it and uses it. In such a situation, the question arises: Who owns the format string? In other words, who is responsible for creating and deleting it and hence controlling its lifetime? Neither the manipulator nor the inserter can own it because they share it.

We solved the problem by requiring the format specification to be created and deleted by the iostream user. Only a pointer to the format string is handed over to the manipulator, and only this pointer is stored through std::ios_base::pword(). Also, we do not copy the format string because it would not be clear who -- the manipulator or the inserter -- is responsible for deleting the copy. Hence the stream user has to monitor the format string's lifetime, and ensure that the format string is valid for as long as it is accessed by the inserter.

This introduces a subtle lifetime problem in cases where the date format is a variable instead of a constant: the stream might be a static stream and hence live longer that the date format variable. This is a problem you always deal with when storing a pointer or reference to additional data instead of copying the data.

However, this subtle problem does not impose an undue burden on the user of our setfmt manipulator. If a static character sequence is provided, as in:

the setfmt manipulator can be used safely, even with iostream objects with static storage duration (for example, cout).



Previous fileTop of DocumentContentsIndex pageNext file